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

时间:2015-09-16 12:03:58

标签: javascript regex

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

var string1 = "Area 51"; // This is the string I have
var match1 = "51"; // This is the string I want

或者这个:

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

有什么想法吗?

2 个答案:

答案 0 :(得分: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);
&#13;
&#13;
&#13;

Regex explanation

\b\d+\b.*$

Regular expression visualization

Debuggex Demo

答案 1 :(得分:0)

使用\b字边界后跟\d来查找以数字开头的字词。

&#13;
&#13;
var str = "Simple test1 String 2where there rand3om number4s through5out.";
alert(str.match(/\b\d.*/)[0]);
&#13;
&#13;
&#13;