Saturday, 15 September 2012

c# - Failing to recognize both keywords -



c# - Failing to recognize both keywords -

let me know if i'm asking question in wrong way. not sure if i'm approaching right angle.

my regex looks this.

^.+(ef?)|(mn?).+$

i'm trying match line 2 , 4 in text below.

abcd efgh ijkl mnop qrst

as seem, lastly 1 catches editors eye. missing?

i've tried follow some examples detecting e.g. "alpha" , "beta" words but, apparently, i'm ignorant of how works.

regex engine split below regex 2 parts.

^.+(ef?)|(mn?).+$ part 1| part 2

at-first, part1 executed.

^.+(ef?)

.+ ensures there must atleast single character nowadays before e, there isn't. fails match sec one. , fails others because there isn't character e nowadays in remaining strings.

| or

now regex engine moves sec part,

(mn?).+$

matches string contains letter m. m nowadays in 4th string. matches m plus next 1 or more characters because of .+.

the right approach match 2 , 4th strings is:

^.*(ef?).*$|^.*(mn?).*$

or

^.*(?:(ef?)|(mn?)).*$

demo

use ^.*(?:(ef?)|(mn?)).+$, if there must character follows e , optional f or m , optional n

if want match strings starts e or m, utilize below regex.

^(ef?|mn?).+$

note:

.* matches character 0 or more times. .+ matches character 1 or more times.

c# regex

No comments:

Post a Comment