Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex or on multiple/single characters

Tags:

regex

I'm dynamically making a regex.

I want it to match the following:

lem
le,,m
levm
lecm

Basically, "lem" but before the m it can have any number of , or any one of any character. Right now I have

le[\,]{0,}[.]?m

you can see it at http://regexr.com?303ne

It should match every one but the third one.

Update: I figured it out:

le[\,]{0,}.?m
like image 953
LemonPie Avatar asked Feb 23 '12 01:02

LemonPie


2 Answers

Whenever you think "or" in Regular Expressions, you should start with alternation:

a|b

matches either a or b. So

any number of a list of characters OR 1 of any character

can be translated quite literally to

[...]*|.

where ... would be the list of characters to match (a character class). If you use that as part of a longer expression, you need to use parentheses, because concatenation binds stronger (has higher precedence) than alternation:

le([,]*|.)m

Because the character class has only one item, we can simplify this:

le(,*|.)m

Note that . by default means "any character but newline".

like image 144
PointedEars Avatar answered Oct 26 '22 23:10

PointedEars


What about this:

le(,*|.?)m

it should do what you want.

like image 26
morja Avatar answered Oct 27 '22 00:10

morja