-1

Consider the following strings:

hotpoint nm11 823 wk eu n 1200 rpm 8 kg class a+++
hotpoint nm11 823 wk eu n rpm 1200 8 kg class a+++
hotpoint nm11 823 wk eu n rpm1200 8 kg class a+++

How could I write a regexp, that will match the highlighted part in either string? Basically, I want a regexp that will match part of a string that either starts with rpm or ends with rpm and contains only spaces and numbers in between.

To do a regexp that starts with rpm and contains only numbers or spaces, I could do something like this:

/((rpm)\s{0,1}(\d+))/

and I also know that I can achieve the desired result by adding an additional | (OR) part to the regexp by this:

/((rpm)\s{0,1}(\d+)|(\d+)\s{0,1}rpm)/

What I am interested in, if there is any other way to specify that the matched part should either start or end with something specific, without duplicating the whole matching rule?

Note, that the part of the string I am looking for is not on the end or the beginning of the string, so I can't use $ or ^

Adam Baranyai
  • 3,635
  • 3
  • 29
  • 68

1 Answers1

1

In some regex flavors, including PCRE and PyPi in Python, if you put a capture group around the pattern, you can match the pattern again elsewhere with (?1) syntax, with the 1 replaced with the capture group index, like this:

(rpm)\s?\d+|\d+\s?(?1)

https://regex101.com/r/neK7cC/1

Note that {0,1} simplifies to ?.

If one isn't lucky enough to be working with an engine that supports recursing subpatterns, one will have to repeat the pattern again, or find out another way.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • as for the operation I am trying to perform, speed is rather important, would this result in a porential speed increase for the regular expression, or it will only be visualizible better by a human person? – Adam Baranyai Nov 27 '20 at 16:01
  • It will depend on the environment the RE is running in and the text that's being examined. The difference may get compiled away, but it might not - run a performance test with the different patterns to find out. – CertainPerformance Nov 27 '20 at 16:04