简体   繁体   中英

Javascript regular expression to match “123” out of test123

In Javascript:

I have a sentence "this is a test123" and i need to match the group of numbers following the word test.

Is there a way to do this other than with using groups?

This is what i got, but i'd like to make this work without using a group (if possible)

var str = str.match(/test.([0-9]{1,3})/)

Basically i just need to say "any number group preceded by 'test'"

Simple single line of code (yet groups, but simple):

"this is a test123".replace(/.*test(\d{1,3}).*/, "$1");  // "123"

Or another version with match :

("this is a test123".match(/test(\d{1,3})/) || []).pop();  // "123"

And one more single line without regex:

parseInt("this is a test123".split("test")[1], 10);  // 123

如果您不喜欢这些组,您可以在一行中使用2个简单的功能:

 str = str.match(/test[0-9]{1,3}/).toString().replace('test', '');

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