Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python RegEx: match words in a string only if they are not preceded by a specific character

For example:

something foo somethingelse // matches: [something, foo, somethingelse]
something1 something.foo-somethingelse // matches: [something1, something, foo, somethingelse]

but not if preceded by ‘>’

something1 something>foo-.somethingelse // matches: [something1, something, somethingelse]

I did develop this regex:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(?(?<!>)(\w+)|\w+)
(? - if
 (?<! - is not preceded by (negative lookbehind)
  > - literal '>'
 )
 (\w+) - capture a group of 1 or more word characters
 | - else
 \w+ - match 1 or more word characters without capturing them
)

which worked in regex101 (words starting with > weren’t included in group 1), but that’s when I learned that conditional regex is either not a thing in Python, or it doesn’t work like in Perl.

Also correct me please if that is not true.

>Solution :

You don’t have to use a conditional, you can use your negative lookbehind assertion and start with a word boundary:

\b(?<!>)\w+

See a regex demo

If you want to use the capture group:

\b(?<!>)(\w+)|\w+

See another regex demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading