How to combine a double quote or a single quote or without quotes with a regular expression?

I am trying to capture sometext from all three input types, but cannot figure out how to deal with an unordered case.

So far I:

name=['"](.*?)['"]

Input:

name="sometext"
name='sometext'
name=sometext
+3
source share
3 answers

It looks like you are a C # developer, so you can use the first matching group to make sure that it is closed with the same quote (and thus supports 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);
+4
source

I would use the OR operator |to indicate three cases separately:

('[^'"]*')|("[^'"]*")|([^'"]*)

regex, , , OR, [^'"]*.

+1

Not knowing what could be after "name = asdf", suppose it is a space or nothing is found that borders the end.

name= 
(?:
     (['"])((?:(?!\1).)*)\1    # (1,2)
 |   (\S*)                     # (3)
)

The answer is $ 2, labeled $ 3

0
source

All Articles