简体   繁体   中英

Javascript Regex I'm struggling with

I am admittedly NOT a regex person but usually I can figure my way around something. This one has me stumped...

I need to match and replace a double greater than str (>>) that has an optional leading space. I know this doesn't work but something along the lines of...

/\s\s+[>>]/

But that's obviously no good.

Would appreciate any help. This site has been an amazing resource for me over the years and I can't believe I'm only getting around to posting something now, so it goes to show even a knucklehead like me has been able to benefit without bothering people... until now:) Thanks in advance.

对于字符串和带前导空格的>>,请尝试:

/(\s*)(>>){1}/

If you want the space to be optional, then you can simply do this :

/>>/

And you may use it as a replacement pattern with the g modifier :

str = str.replace(/>>/g, 'something') 

If you want to check that a string is >> with maybe some space before, then use

/^\s?>>$/

This regex should work.

/\s*[>]{2}/

This is cleaner

/\s*>>/

Tested:

var pattern = /\s*>>/;
s1 = "             >>";
s2 = ">>";
s3 = ">> surrounding text";
s4 = "surrounding  >> text";
s5 = "surrounding>>text";

s1.match(pattern);
["             >>"]
s2.match(pattern);
[">>"]
s3.match(pattern);
[">>"]
s4.match(pattern);
["  >>"]
s5.match(pattern);
[">>"]

Replacement example

var pattern = /\s*>>/;
var s6 = "    >> surrounding text";
s6.replace(pattern, ">");
"> surrounding text"

If you want it to match an unlimited amount of leading space characters:

/ *>>/

If you want it to match 0 or 1 leading space character:

/ ?>>/

Breaking down your example:

  1. \\s will match any white-space character
  2. \\s+ will match one or more white-space characters
  3. [>>] will match one > (see more below on this)

So your expression will match a > preceeded by at least two white-space characters.

If you want to match zero-or-more you will have to use * ; fex \\s* .

Square brackets are used to denote sets of characters, and will match any of the characters in the set; fex [abc] will match a, b or c, but only one character at time.

Single characters in a regular expression will match that character; fex > will match one greater-than sign.

Putting it together we get the following regular expression for your case:

/\s*>>/

This should work with the optional space.

/\s{0,}>>/g

Visit this link to test the matches.

用这个 :

str.replace(/\s+>>/g, 'whatever'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM