I was creating some regex for matching strings like :
'pulkit'
'989'
basically anything in between the two single quotes.
so I created a regex something like ['][^']*[']
.
But this is not working for cases like:
'burger king's'. The expected output is burger king's
but from my logic
it is burger king
only.
As an another example 'pulkit'sharma'
the expected output should be pulkit'sharma
So can anyone help me in this ? How to escape single quotes in this case.
CodePudding user response:
Try a positive lookahead to match a space or end of line for matching the closing single quote
'. ?'(?=\s|$)
CodePudding user response:
You may match single quote that is not preceded with a word char and is followed with a word char, and match any text up to the '
that is preceded with a word char and not followed with a word char:
(?s)\B'\b(.*?)\b'\B
See the .NET regex demo.
Note you do not have to wrap single quotation marks with square brackets, they are not special regex metacharacters.
C# code:
var matches = Regex.Matches(text, @"(?s)\B'\b(.*?)\b'\B")
.Cast<Match>()
.Select(x => x.Groups[1].Value)
.ToList();