简体   繁体   中英

Javascript regular expression match on string followed by number?

I have a string of the format: string:num where num is any number but string is a known string that I need to match on. I'd like to have this in an if statement as:

if( it matches 'string:' followed by a number) {
   //do something
}

You want ...

if (stringYouHave.match(/^string:([0-9]+)$/)) {
    // do something
}

This includes:

  1. ^ beginning of the string
  2. string: the literal "string:" you mentioned
  3. (.....) This subexpression, which you can refer to later if you need to know which number is in the string (though in this particular case, you could also just replace 'string:' with '' )
  4. [0-9] a character between 0 and 9 (ie, a digit)
  5. + Must have at least one "of those" (ie, digits mentioned above), but can have any number
  6. $ end of the string
if( it.match(/^string:\d+$/) ( {
   ...
}

If you want only to check if the input string matches the pattern, you can use the RegExp.test function:

if (/^string:[0-9]+$/.test(input)){
  //..
}

or with the String.search function:

if (input.search(/^string:[0-9]+$/) != -1){
  //..
}

If you want to validate and get the number:

var match = input.match(/^string:([0-9]+)$/),
    number;

if (match){
  number = +match[1]; // unary plus to convert to number
  // work with it
}

The above is good for integer numbers; if you want floating point numbers, or even scientific notation (as understood in C-like languages), you'll want something like this:

if (stringYouHave.match(/^string:[+-]?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?$/))
{
    // do something
}

You can remove the first [+-]? if you don't care about sign, the (.[0-9]+)? if you don't care about floating points, and the ([eE][+-]?[0-9]+)? if you don't care about scientific notation exponents. But if there's a chance you DO want to match those, you want to include them as optional in the regex.

if(teststring.match(new RegExp("^" + knownstring + ":\d+$"))) {
  // some code
}
if(!!"string:5456".match(/^string:\d+$/)) { ... }

Number是上例中的整数。

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