Junius L
Junius L

Reputation: 16152

Regex match when is followed by a space or no space

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.

enter image description here

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

Answers (1)

schorsch
schorsch

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

Related Questions