如何使用正则表达式和Javascript获得以数字开头的第一个单词?

Web*_*urk 0 javascript regex

我无法弄清楚如何编写一个正则表达式模式来捕获在第一个数字之后开始的所有单词.为清晰起见,下面两个例子

var string1 = "Area 51"; // This is the string I have
var match1 = "51"; // This is the string I want
Run Code Online (Sandbox Code Playgroud)

或这个:

var string2 = "A simple sentence with 6 words or more" // This is the string I have
var matchedString = "6 words or more" // This is the string I want
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Pra*_*lan 5

您可以使用正则表达式\b\d+\b.*$和方法match()进行模式匹配

var string1 = "Area 51"; // This is the string I have
var match1 = string1.match(/\b\d+\b.*$/)[0];

var string2 = "A simple sentence with 6 words or more" // This is the string I have
var matchedString = string2.match(/\b\d+\b.*$/)[0]; // This is the string I want

document.write(match1+'<br>'+matchedString);
Run Code Online (Sandbox Code Playgroud)

正则表达式解释

\b\d+\b.*$
Run Code Online (Sandbox Code Playgroud)

正则表达式可视化

Debuggex演示