Regular expression check if none empty word is not a specific word

Viewed 333

I want to find a way to match a string in a specific pattern: <not 'self'>._<something>.

This pattern should match these strings

object._attr
a._aaa

And any other strings with that pattern, as long as the first part before the dot ('object' and 'a') is not empty, and is not the literal string 'self'. And the second part after the underscore ('attr' and 'aaa') must not be empty and must contain only word characters. So self._attr, object._ will not be matched.

Currently I'm trying to use negative look-ahead like this

(?!self)\._(\w+?)

But the problem is that this pattern still matches self._attr, since the negative look-ahead matches the empty string before the dot.

How do I actually specify that the first part of the pattern has to be non-empty.

Hopefully I phrased my question well.

Thanks everyone

3 Answers

You can try

^((?!self).)+\._(\w+?)$

enter image description here

Regex demo


If you're not matching up the complete string, you're trying to match the sub parts of string also, then instead of anchors you can use wordboundary or lookarounds

Using lookaround

(?<!\S)((?!self).)+\._(\w+?)(?!\S)

Using word bouandry

\b((?!self).)+\._(\w+?)\b

If you want to match only alphabets you can replace . by [a-zA-Z]

^((?!self)[a-zA-Z])+\._(\w+?)$

You could do this using -

((?!self)\w)+\.\w+

It will be a bit slower than normal since regex was not made with negation in mind but it is possible.

*the + ensures that there is at least one character so you know the first part is not empty

You could also exclude what you don't want by matching it and keep in a group what you do want.

\bself\._\w*|(\w+\.\_\w+)
  • \bself\._\w* Word boundary, match self._ and 0+ word chars
  • | Or
  • ( Capture group 1
    • \w+\.\_\w+ Match 1+ word chars ._ and 1+ word chars
  • ) Close group

Regex demo | Python demo

Related