简体   繁体   中英

Regex - letter followed by any number of digits

I am trying to match a string with a regex condition. It doesn't seem to be working though. It will always be capital D

var string = 'D123';

var matchVar = string.match(/^D+[0-9]^/);

if(matchVar){
    alert('yes');
}

DEMO http://jsfiddle.net/chwprLg1/

You need to replace the last ^ with + . + repeat the previous token one or more times. So [0-9]+ matches one or more digits. You cud use \\d instead of [0-9]

var matchVar = string.match(/^D+[0-9]+/);

Without the end of the line anchor, the above regex would also match D98 in D98foobar .

OR

One or more D 's followed by any number of digits.

 var matchVar = string.match(/^D+[0-9]+$/);

OR

A single letter followed by any number of digits.

var matchVar = string.match(/^D[0-9]+$/);
^D+[0-9]+$

Guess you wanted this. ^ asserts start of string.See demo.

https://www.regex101.com/r/rC2mH4/13

or

^D+\d+$

var string = 'D123';

var matchVar = string.match(/^D+\d+$/);

if(matchVar){
    alert('yes');
}

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