Reputation: 785
This regex below captures the -aaaa and -cccc but not the -eee How can I do that?
keywords = "-aaa bbb -ccc -eee";
MatchCollection wordColNegEnd = Regex.Matches(keywords, @"-(.*?) ");
Upvotes: 0
Views: 120
Reputation: 126722
Use a "word boundary" /\b/
instead of a space, which matches the end of the string as well as a word/non-word boundary:
Regex.Matches(keywords, @"-(.*?)\b");
or, depending on what characters may be in the strings, just use "word characters" /\w/
to match the pattern:
Regex.Matches(keywords, @"-(\w+)");
Upvotes: 2
Reputation: 35265
You haven't specified what exactly you are trying to match here.
But if I understood it right, you want to match any alpha string that starts with -
Use this RegEx: -[a-z]+
Upvotes: 0
Reputation: 776
keywords = "-aaa bbb -ccc -eee";
MatchCollection wordColNegEnd = Regex.Matches(keywords, @"-\w+");
Upvotes: 0
Reputation: 31250
Use
MatchCollection wordColNegEnd = Regex.Matches(keywords, @"-(.+?)\b");
Upvotes: 1
Reputation: 71565
Currently, your regex requires a trailing space behind the capturing group. the strings "aaa" and "ccc" have this, but "eee" does not.
Instead of matching any characters occurring after a dash, try matching nonspace characters:
@"-(\S*?)"
Upvotes: 0
Reputation: 19203
MatchCollection worldColNegEnd = Regex.Matches(keywords, @"-(.*?)\b"
Word boundary is better than space, please give someone else upvotes though, since I brain farted the purpose of it.
Also I don't know why you included a ?
in your original so I left it, but I believe it is not necessary, as *
matches 0 or more matches.
Upvotes: 1