2

I'm trying to parse length quantities that use Imperial shorthand notation (' for feet, " for inches), and I'm in a bit of a quandary. Using this regular expression:

/\d+(\.\d+)?(?:[ -]\d+\/\d+)?(?:\')/g

I can match the following strings (each passed separately within a larger string):

  • 5'6" (matches 5')
  • 6'
  • 3 1/2'
  • 12.5'

However, I've run across strings where '' is used in place of ". I tried adding [^\'] at the end, but that would match 5'6 in the first example, and if I put [^\'\d], it wouldn't match the first example at all. Any help?

Matt
  • 2,576
  • 6
  • 34
  • 52

1 Answers1

2

In order to match 5' in 5'6'', you just need to use a negative lookahead:

/\d+(?:\.\d+)?(?:[ -]\d+\/\d+)?'(?!')/g
                                ^^^^^

See regex demo

The (?!') will fail the whole match if a ' at the end is followed with another single apostrophe.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • @Ciastopiekarz It does not have to. The pattern is not meant to match any double quotes. You need a different pattern, like `\d+'\d+"`. If the `\d+"` part is optional, just wrap it with a non-capturing group and quantify it with `?`: ``\d+'(?:\d+")?``, see [How do I make part of a regex match optional?](https://stackoverflow.com/questions/12451731). – Wiktor Stribiżew Jan 22 '21 at 19:36