How to match double quote or single quote or unquoted with regular expression?

前端 未结 3 526
后悔当初
后悔当初 2021-01-14 09:34

I am trying to grab sometext from all three types of inputs, but can\'t figure out how to deal with the unquoted case.

So far I have:

name=[\'\"](.         


        
3条回答
  •  既然无缘
    2021-01-14 10:04

    It looks like you are a C# developer, so you can use the first matching group to ensure it is closed off with the same quote (and thus support phrase="Don't forget apostrophes").

    Regex regex1 = new Regex(@"=(?:(['""])(.*?)\1|.*)");
    
    string text = @" 
    name=""don't forget me""
    name='sometext'
    name='sometext'
    name=sometext
    ";
    
    foreach (Match m in regex1.Matches(text))
       Console.WriteLine (m.Groups[2].Value);
    

提交回复
热议问题