Peter Berg
Peter Berg

Reputation: 6206

Regex to match a space character preceded by a space character

I'd like to write a regex to match the marked characters marked with a '^' in the following string

this  is    a     string
     ^   ^^^  ^^^^ 

But I'm confused about

a) how to match a character based on the character preceding it, and

b) how to match a space that is really just a space and not a tab (\t) or a new line (\n) char

I need this to work in javascript, if that makes any difference.

Any thoughts?

Upvotes: 3

Views: 3810

Answers (2)

Shawn G.
Shawn G.

Reputation: 622

Just use String.replace( regexp , replaceWith )

and use the RegExp /([ ]+)/g

This will replace any space preceeded with any number of spaces with just a space

var string = "I have multiple spaces .";

Then, you would use a custom function to replace it with.

var marked = string.replace(/([ ]+)/g, function( p1 ){
    return " " + p1.slice(0,-1).replace(/[ ]/g, ' ');
});

Here is a fiddle with a working example http://jsfiddle.net/h5C7p/

Upvotes: 1

Jacob
Jacob

Reputation: 78920

Because of the lack of lookbehinds, the best you can do is find the overall match using this, and then just use capture group 1:

/(?: )( +)/g

Or, in whatever code uses the match information, just assume that the first character is a space, and use this regex:

/ +/g

Upvotes: 4

Related Questions