Reputation: 16152
Hi how can I write regex for matching a word only when there's a space before the word or no space?
currenlty my regex is like this /(R)(\ )([0-9]+)/gi
and it matches the word that is not followed by a space.
I want to match R 23, r30 if it is followed by a space or no space.
for example:
const str = 'R 34 r 45, for 2 a day';
console.log(str.replace(/(R)(\ )([0-9]+)/gi,'R$3'))
//prints "R34R45, foR2 a day"
//expected "R34 R45, for 2 a day"
Upvotes: 0
Views: 277
Reputation: 46
You need word boundary before R and no need for capture, can use lookahead instead.
Search: \bR (?=\d)
and replace with R
Upvotes: 3