Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression not matching specific string

Tags:

regex

My use case is as follows: I would like to find all occurrences of something similar to this /name.action, but where the last part is not .action eg:

  • name.actoin - should match
  • name.action - should not match
  • nameaction - should not match

I have this:
/\w+.\w*
to match two words separated by a dot, but I don't know how to add 'and do not match .action'.

like image 207
Ula Krukar Avatar asked Dec 10 '09 15:12

Ula Krukar


People also ask

Does string match regex?

Regex doesn't work in String.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


2 Answers

Firstly, you need to escape your . character as that's taken as any character in Regex.

Secondly, you need to add in a Match if suffix is not present group - signified by the (?!) syntax.

You may also want to put a circumflex ^ to signify the start of a new line and change your * (any repetitions) to a + (one or more repititions).

^/\w+\.(?!action)\w+ is the finished Regex.

like image 136
Daniel May Avatar answered Nov 05 '22 03:11

Daniel May


^\w+\.(?!action)\w*
like image 38
ʞɔıu Avatar answered Nov 05 '22 03:11

ʞɔıu