8

I want to match any word that starts/ends or not contain with word "end" but ignore word "end", for example:

  • hello - would match
  • boyfriend - would match
  • endless - would match
  • endend - would match

but

  • end - would NOT match

I'm using ^(?!end)).*$ but its not what I want.

Sorry for my english

moebarox
  • 91
  • 1
  • 1
  • 6

3 Answers3

11

Try this:

^(?!(end)$).+$

This will match everything except end.

NID
  • 2,835
  • 1
  • 15
  • 25
0

So you want to match any word, but not "end" ?

Unless I'm misunderstanding, a conditional statement is everything that is needed... In pseudocode:

if (word != "end") {
    // Match
}

If you want to match all the words in a text that are not "end" you could just remove all the non-alpha characters, replace pattern (^end | end | end$) by an empty string, and then do a string split. The other answers with a single regex might be better then, because regex matches are O(n), no matter of the pattern.

Antoine C.
  • 3,193
  • 3
  • 26
  • 51
0

You can use this \b(?!(?:end\b))[\w]+

Components: \b -> Start of the word boundary for each words. (?! Negative lookahead to eliminate the word end. (?:end\b) Non capturing parenthesis with the word end and word boundary. ) Closing tag for negative lookahead. [\w]+ character class to capture words.

Explanation: The regex search will only look for locations starting with word boundaries, and will remove matches with end as only word. i.e [WORD BOUNDARY]end[END OF WORD BOUNDARY]. \w will capture rest of the word. You can keep incrementing this character class if you wish to capture some special characters like $ etc.

Abhishek
  • 2,183
  • 3
  • 30
  • 41