Regex for multiple word match seperated by spaces

Viewed 73

I want to match all occurences of a word in a string having spaces at front and back.

Eg: String: " Apple Apple Apple Apple ".

Here I want the match to be " Apple " and there should be 4 matches for the above scenario.

If I just put regex as / Apple /, then only 1st and 3rd are matched.

I know that we can do this with lookahead and lookbehind in regex but it is not supported in safari and IE.

2 Answers

You can match Apple and assert a space to the right. As you know that the space is there, you can add it in the result.

const regex = / Apple(?= )/g;
const s = " Apple Apple Apple Apple ";
console.log(Array.from(s.matchAll(regex), m => m[0] + " "));

Or you can capture Apple in group 1, and get the group 1 value denoted by m[1] in the code:

const regex = /(?=( Apple ))/g;
const s = " Apple Apple Apple Apple ";
console.log(Array.from(s.matchAll(regex), m => m[1]));

If you're happy to just match the Apple word, you can use (?<= )Apple(?= ).

If the space is not strictly necessary (e.g. you want also to catch the first word of the string, which is not preceded by a space), you must use word boundaries (i.e. \bApple\b).

Related