Reputation: 2220
I want to find the words in a sentence between spaces. So the words till the first space before and after the search word
This is anexampleof what I want
should return anexampleof
if my search word is example
I now have this regex "(?:^|\S*\s*)\S*" + searchword + "\S*(?:$|\s*\S*)"
but this gives me an extra word in the beginning and the end.
'This is anexampleof what I want' --> returns 'is anexampleof what'
I tried to change the regex but I'm not good at it at all.. I'm using c#. Thx for the help.
Full C# code:
MatchCollection m1 = Regex.Matches(content, @"(?:^|\S*\s*)\S*" + searchword + @"\S*(?:$|\s*\S*)",
RegexOptions.IgnoreCase | RegexOptions.Multiline);
Upvotes: 3
Views: 3966
Reputation: 44289
You can simply leave out the non-capturing groups at the end:
@"\S*" + searchword + @"\S*";
Due to greediness you will get as many non-space characters on each side as possible.
Also, the idea of non-capturing groups is not, that they are not included in the match. All they do is not to produce captures of sub-matches. If you wanted to check that there is something, but don't to include it in the match, you want lookarounds:
@"(?<=^|\S*\s*)\S*" + searchword + @"\S*(?=$|\s*\S*)"
However these lookarounds don't really do anything in this case, because \s*\S*
is satisfied with an empty string (because *
makes both characters optional). But just for further reference... if you want to make assertions at the boundary of your match, which should not be part of the match... lookarounds are the way to go.
Upvotes: 3