user713813
user713813

Reputation: 785

regex between characters including end

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

Answers (6)

Borodin
Borodin

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

Moon
Moon

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

ahazzah
ahazzah

Reputation: 776

keywords = "-aaa bbb -ccc -eee";
MatchCollection wordColNegEnd = Regex.Matches(keywords, @"-\w+");

Upvotes: 0

amit_g
amit_g

Reputation: 31250

Use

MatchCollection wordColNegEnd = Regex.Matches(keywords, @"-(.+?)\b");

Upvotes: 1

KeithS
KeithS

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

Guvante
Guvante

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

Related Questions