Regex to replace up to 4 digits before a word

Viewed 70

I am using this extension for chrome (It's called Word Replacer II) and I'm trying to create a Regex find and replace.

Quick backstory, my partner is recovering from an eating disorder and I want to find all mentions of Kilojoules and kJs and replace them with .

I am entirely new to Regex and after a few hours, I'm not much closer to getting a working expression.

I need it to remove up to 4 digits before the letters "kJs". E.g, 400kJs and 1000kJs. I'd like the "400kJs and 1000kJs" to be replaced with "[removed kJs] and [removed kJs]".

The code I have put together so far is;

\s+(a{1,4}<=\d)\s+(?=kJ)

And help would be much appreciated!

1 Answers

You may use the following approach:

\d{1,4}\s*kJs\b

See the regex demo

If you need to keep kJs, you may wrap the right part of the pattern with a lookahead, \d{1,4}(?=\s*kJs\b).

If you do not want to touch 5 or more digit numbers, use

\b\d{1,4}\s*kJs\b
(?<!\d)\d{1,4}\s*kJs\b

That is, add a word boundary, \b, or a left-hand digit boundary, (?<!\d).

Pattern details

  • \d{1,4} - one to four digits
  • \s* - 0+ whitespaces
  • kJs - a string of letters
  • \b - a word boundary (may not be necessary if there can be no word starting with kJs).
Related