简体   繁体   中英

How to find occurence of multiple strings in a given string using javascript RegExp()

I wanted to check the availability of multiple strings in a given string ( without using a loop ).

like

my_string = "How to find occurence of multiple sting in a given string using javascript RegExp";
// search operated on this string
// having a-z (lower case) , '_' , 0-9 , and space

// following are the strings wanted to search .( having a-z , 0-9 , and '_')

search_str[0]="How";
search_str[1]="javascript";
search_str[2]="sting";
search_str[3]="multiple";
  • I don't need their position.
  • I just needed to know all the search_str are must be in my_string .
  • order of search_str never effect the result .

is there is any regular expression available for this ?

UPDATE : WHAT AM I MISSING

in the answers i found this one is working in the above problem

if (/^(?=.*\bHow\b)(?=.*\bjavascript\b)(?=.*\bsting\b)(?=.*\bmultiple\b)/.test(subject)) {
    // Successful match
}

But in this case it is not working.

m_str="_3_5_1_13_10_11_";
search_str[0]='3';
search_str[1]='1';
tst=new RegExp("^(?=.*\\b_"+search_str[0]+"_\\b)(?=.*\\b_"+search_str[1]+"_\\b)");
if(tst.test(m_str)) alert('fooooo'); else  alert('wrong');
if (/^(?=.*\bHow\b)(?=.*\bjavascript\b)(?=.*\bsting\b)(?=.*\bmultiple\b)/.test(subject)) {
    // Successful match
}

This assumes that your string doesn't contain newlines. If it does, you need to change all the . s to [\\s\\S] .

I have used word boundary anchors to make sure that Howard or resting don't accidentally provide a match. If you do want to allow that, remove the \\b s.

Explanation:

(?=...) is a lookahead assertion: It looks ahead in the string to check whether the enclosed regex could match at the current position without actually consuming characters for the match. Therefore, a succession of lookaheads works like a sequence of regexes (anchored to the start of the string by ^ ) that are combined with a logical && operator.

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