简体   繁体   中英

trying to get a regex match in javascript with certain letter followed by any number

I'm trying to get a regular expression to work, but it isn't. It must be a small thing, but I could use some help. I tried using the regex tester at https://regex101.com/ and it said I wasn't doing it right, but it isn't working in my code.

I want to look at a string and see if there's a match for:

space letter v or V no space number between 0 and 9 space letter t or T no space number between 0 and 9 space

Example: " v5 t2 " or " V5 T2 "

Here's javascript/jquery:

if (mystring.indexOf(/v[0-9] t[0-9]/i) > -1) {
    console.log("found!");
} else {
    console.log("not found!");
}

Can anyone tell me what I'm doing wrong, please? I'm new to regular expressions.

indexOf doesn't accept a regular expression, it accepts a string. So your regex is converted to string, which then doesn't match.

If you want to check for a match, use RegExp#test :

if (/v[0-9] t[0-9]/i.test(mystring)) {
    // Yes
} else {
    // No
}

Note that looks anywhere in the string.

Also note that [0-9] is \\d , so the regex could be /v\\dt\\d/i .

 var mystring = "foo V5 T7 bar"; if (/v\\dt\\d/i.test(mystring)) { console.log("found!"); } else { console.log("not found!"); } 

If you needed to know where the match occurred, you'd use String#match or RegExp#exec instead, and look at the index property of the result:

 var mystring = "foo V5 T7 bar"; var match = /v\\dt\\d/i.exec(mystring); if (match) { console.log("Found at " + match.index); } else { console.log("Not found"); } 

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