开发者

Ignoring certain chars globally

Consider it that '_'s in 开发者_开发技巧a number doesn't change that number's value so 1000==1_000==10_00.

The Problem: given numbers like 1_244_23 1412_2 1_1111 etc..., how could I decide whether certain number appears in that collection? For example: 1244_23 yes, 11_111 yes, 1412_1 no.

How could using regex to solve this? I mean, if I could tell the regex engine just ignore these '_''s when matching then this problem becomes trivial? How could I do so?


Don't make it more complex than it has to be.

var baseStr = "1_244_23 1412_2 1_1111";
var testFor = "1244_23";

var contains = !!new RegExp("\\b" + testFor.replace(/_/g,"") + "\\b").exec(baseStr.replace(/_/g,""));


You can make a regular expression that allows for an underscore at any position:

var input = '1_244_23 1412_2 1_1111';
if (/(^|\s)1_?1_?1_?1_?1(\s|$)/.exec(input) != null) {
  ...
}

If you want to create the regular expression from a string:

var input = '1_244_23 1412_2 1_1111';
var number = '11_111';
var re = new Regex('(^|\s)'+number.replace(/_/g, '').replace(/\B(.)/g, '_?$1')+'(\s|$)');
if (re.exec(input) != null) {
  ...
}

Edit:

I added (^|\s) and (\s|$) to the regular expressions to match the start and end of a number, so that a number like 111 doesn't get a false positive matching 21113.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜