开发者

Javascript regex parsing

开发者 https://www.devze.com 2023-02-19 10:00 出处:网络
I\'m looking to parse some formatting out of a field using javascript. My rule is catching some extra things which I need to fix. The regex is:

I'm looking to parse some formatting out of a field using javascript. My rule is catching some extra things which I need to fix. The regex is:

/[\((\)\s)-]/g

This regex is properly cleaning up: (123) 456-7890 the problem I'm having is that it is also removing all spaces rather than just spaces following a closing parentheses. I'm no expert in regex but it was my understanding that (\)\s) would only remove the closing parentheses and space combo. What would the correct regex look like? It needs to remove all parentheses and dashes. Also, only remove spaces 开发者_如何学Goimmediately following a closing parentheses.

The outcomes I would like are such.

The replace method i am using should work as such

var str = mystring.replace(/[\((\)\s)-]/g, '');

(123) 456-7890 should become 1234567890 which is working.

leave me alone should stay leave me alone the issue is that it is becoming leavemealone


This will do the job:

var str = mystring.replace(/\)\s*|\(\s*|-/g, '');

Explanation of the regex:

\)\s* : Open parenthesis followed by any number of whitespace
|     : OR
\(\s* : Close parenthesis followed by any number of whitespace
|     : OR
-     : Hyphen

Since parenthesis are regex-metacharacters used for grouping they need to be escaped when you want to match them literally.


Placing everything in brackets ([]) creates a class of characters to match anywhere in the input. Taking your requirements literally ("remove all parentheses, dashes and spaces immediately following a closing parentheses"):

"(123) 456-789 0".replace(/\)[\(\)\s-]+/g, ")")

Output:

"(123)456-789 0"

This matches (essentially) the same character class, but specifies that these characters immediately follow a closing parenthesis.


You could use lookbehind to ensure that there is a paranthesis or something else preceding the space:

(?<=\))\s

------------ OLD ANSWER ----------

If you want to remove all paranthesis, dashes and spaces, you would go with something like this:

/[\s-\(\)]+/g

[something] - would look for anything that is in the brackets (letters s, o, m, e, t, h, i, n, g).

\s = white space

( = paranthesis

) = paranthesis

+ = at least one or more occurance of what is preceding it (which would be paranthesis, white space and dashes)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号