michael-martinez
michael-martinez

Reputation: 797

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:

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

Upvotes: 2

Views: 145

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

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.

Upvotes: 3

Related Questions