Home > Software design >  Regular expression with condition on inner expressions
Regular expression with condition on inner expressions

Time:06-30

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 " ?

CodePudding user response:

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.
  • Related