简体   繁体   中英

Regex match all strings containing a given series of letters or digits

I have a search box and i need to grab the value of this search and match all DIV which data-* value is starting with the search value.

Cases:

Search value: 201

Should match : data-year="2011" , data-year="2012" , data-year="2013"

Should fail : data-year="2009" , data-year="2001"

This is what i come up with so far:

\\b(?=\\w*[" + token + "])\\w+\\b

token is a dynamic value from the search box. Therefore i need to use RegExp

This is working but it match all the value which contain 2 or 0 or 1 (for my understanding). so 2009 is valid match as well. :/

I also try to add the caret at the beginning in order to match the characthers just at the beginning of the world but clearly i'm missing something here:

^\\b(?=\\w*[" + token + "])\\w+\\b

The whole code is:

var token = '200'; // should fail
var tokenTwo = '201'; // shoudl work
var dataAtt = $('#div').data('year').toString(); 
var regexExpression ="^\\b(?=\\w*\\d*[" + token + "])\\w+\\d+\\b";
var regEXPRES = "^.*" + token + ".*$";
var regex = new RegExp(regexExpression, "i");

if( dataAtt.match(regex) ){
 console.log(dataAtt);

alert('yey!!!');
} else {
    alert('nope!! )')
}

and here is the JsFiddle http://jsfiddle.net/tk5m8coo/

ps I shouldn't have any cases where token is precede or follow by other characters, but if anyone as idea how to check also this, would be great. Just in case of any typo like s2015.

Or you can use indexOf() :

 var value = '20'; var html = $("#div").html(); var dataAtt = $('#div').data('year').toString(); if( dataAtt.indexOf(value) >= 0 ){ console.log('yey!!!'); } else { console.log('nein!! )') } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id ="div" data-year="2015"> what bozo where 2015 </div> 

Problem is that you're putting your search value inside a character class when you enclose your regex by wrapping around [...] .

You also don't need a lookahead. You can just use:

var regex = new RegExp("\\b\\w*" + value + "\\w*\\b");

To make sure search value is matched within a full word. ( \\w includes digits also so no need to use \\d ).

Full code:

var value = '20'; //token
var html = $("#div").html(); //data.()
var dataAtt = $('#div').data('year').toString(); 

var regex = new RegExp("\\b\\w*" + value + "\\w*\\b");

if( dataAtt.match(regex) ){
   console.log(dataAtt + " matched");
} else {
   console.log('nope')
}

Updated JS Fiddle

Your regex is using a character class which will match any of the characters inside the square brackets. Remove the square brackets:

^\\b(?=\\w*" + token + ".*)\\w+\\b 

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