Reputation: 1414
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=['"](.*?)['"]
Input:
name="sometext"
name='sometext'
name=sometext
Upvotes: 3
Views: 11423
Reputation:
Without knowing what could be after 'name=asdf', assume its whitespace or nothing
that delimits the end.
name=
(?:
(['"])((?:(?!\1).)*)\1 # (1,2)
| (\S*) # (3)
)
Answer is $2 catted with $3
Upvotes: 0
Reputation: 27903
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);
Upvotes: 4
Reputation: 39733
I would use the OR operator |
to specify the three cases separatly:
('[^'"]*')|("[^'"]*")|([^'"]*)
Depending on the regex dialect you are using, you have to define non matching groups separated by the OR operators, and matching groups for the words [^'"]*
.
Upvotes: 2