开发者

JS - RegExp for detecting ".-" , "-."

开发者 https://www.devze.com 2023-03-27 20:44 出处:网络
I am bit confused with the RegExp I should be using to detect \".-\", \"-.\" it indeed passes this combinations as valid but in the same time, \"-_\",\"_-\" get validated as well. Am I missing somethi

I am bit confused with the RegExp I should be using to detect ".-", "-." it indeed passes this combinations as valid but in the same time, "-_","_-" get validated as well. Am I missing something or not escaping something properly?

 var reg=new RegExp("(\.\-)|(\-\.)");开发者_如何学编程

Actually seems any combination containing '-' gets passed. it

Got it thank you everyone.


You need to use

"(\\.-)|(-\\.)"


Since you're using a string with the RegExp constructor rather than /, you need to escape twice.

>>> "asd_-ads".search("(\.\-)|(\-\.)")
3
>>> "asd_-ads".search(/(\.\-)|(\-\.)/)
-1
>>> "asd_-ads".search(new RegExp('(\\.\-)|(\-\\.)'))
-1


In notation /(\.\-)|(\-\.)/, the expression would be right. In the notation you chose, you must double all backslashes, because it still has a special meaning of itself, like \\, \n and so on.
Note there is no need to escape the dash here: var reg = new RegExp("(\\.-)|(-\\.)");

If you don't need to differentiate the matches, you can use a single enclosing capture, or none at all if you only want to check the match: "\\.-|-\\." is still valid.


You are using double quotes so the . doesn't get escaped with one backslash, use this notation:

var reg = /(\.\-)|(\-\.)/;
0

精彩评论

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