How can I prevent the words I am looking for from repeating, regardless of their order?

I spent one hour trying to make a better regex, but this is not my cup of tea ... I need a regex that will do the following (can provide more if needed):

Spd_Engine          #Ok
speedengine         #Ok
enginespd           #Ok
Engine_speed        #Ok
aps_speed_engine    #Ok
engine_speed        #Ok
engine_trq          #Not Ok
speed_rpm           #Not Ok

      

Regex shoud matches every line that contains at least (engine && (speed || spd))

So I came up with this:

[e,E]ngine[_]?[s,S]p[e]*d|[a-zA-Z]*[_]*[s,S]p[e]*d[_]?[e,E]ngine

      

But I feel it can be improved. How can I simplify it?

+3


source to share


2 answers


You can use perspective to simplify the regex just like

^(?=.*spe*d)(?=.*engine).*

      

  • ^

    Anchors a regular expression at the beginning of a line

  • (?=.*spe*d)

    a positive look ahead. Checks if a string containsspe*d

  • (?=.*engine)

    another positive view. Checks if a string containsengine

  • .*

    matches the whole line

Regex example

OR



^(?=.*spe*d).*engine.*

      

Hacking a second look ahead

Regex example

Notes to [e,E]ngine[_]?[s,S]p[e]*d|[a-zA-Z]*[_]*[s,S]p[e]*d[_]?[e,E]ngine

  • [e,E]

    commas within a character class do not mean a e

    comma e

    . You can change it like

    [eE]

  • [_]?

    There is no advantage in adding one character to a character class. It's simlar like wirting_?

  • i

    the i flag can be used to ignore cases when a regex matches

+9


source


So, if the shorter version of this regex is considered a simplification, then this is what came to my mind.

[e, e] ngine _ [S, S] PED |? [A-Za-Z] _ [S, S] PED _ [e, e] ngine



VS

?

[e, e] ngine [] [s, s] p [e] * d | [A-Za-Z] * [] * [S, S], p [e] * d [_]? [e, e] ngine

0


source







All Articles