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

Regular expression with condition on inner expressions

I would like to build a regular expression for replacing a sentence with "per" when it should be (a readable version of a sentence with quantities).

That is:

  • "3/unit" must match
  • "unit/3" must match
  • "feet/second" must match
  • "05/07" must not match

I know how to create something like "\D+/\D+".
But how can I build a regex saying "not both right and left expressions match \D+" ?

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

>Solution :

You can use

^(?![0-9]+/[0-9]+$)[^/]+/[^/]+$

See the regex demo. Details:

  • ^ – start of string
  • (?![0-9]+/[0-9]+$) – a negative lookahead that fails the match if there are one or more digits, /, one or more digits and end of string position immediately to the right of the current location
  • [^/]+/[^/]+ – one or more chars other than /, a / char, and then one or more chars other than /
  • $ – end of string.
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