admin管理员组

文章数量:1432752

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?

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?

Share Improve this question edited Apr 18, 2019 at 13:07 Peter Berg asked Nov 21, 2013 at 23:31 Peter BergPeter Berg 6,2268 gold badges40 silver badges51 bronze badges 13
  • 2 do you try to remove duplicate spaces? – Casimir et Hippolyte Commented Nov 21, 2013 at 23:35
  • 3 In javascript, there is no lookbehinds. So you'll need to match that space and put the others in a matching group (or vice versa depending on your goals) : space(space+) -> replace space with a literal space 0x20 – HamZa Commented Nov 21, 2013 at 23:35
  • 2 @putvande: you forget the b) requirement. – Casimir et Hippolyte Commented Nov 21, 2013 at 23:36
  • 2 Why? You could just use white-space: pre; on the element containing the text (which is far easier). – David Thomas Commented Nov 22, 2013 at 0:01
  • 3 white-space: pre preserves the white-space (prevents it being collapsed down to a single space) in an element, as it was entered into the HTML. – David Thomas Commented Nov 22, 2013 at 0:09
 |  Show 8 more ments

2 Answers 2

Reset to default 4

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

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/h5C7p/

本文标签: javascriptRegex to match a space character preceded by a space characterStack Overflow