提取所有以数字开头的单词

时间:2020-07-24 09:10:53

标签: javascript regex

我也得到了类似以下格式的字符串,

"24" // only numbers
"23_hell,23,67,990_test" // number followed by _ followed by string (it repeats with comma)

它不应该匹配不以数字开头的单词,例如textabc123

我在正则表达式下使用过,但无法正常工作:

var val = "23_hell text 23 abc123 45_dell"
val.match(/\d+/g);  

这将返回如下:

["23","23","123","45"]

但是我需要的是

["23_hell","23","45_dell"]

2 个答案:

答案 0 :(得分:2)

要提取所有以数字开头的单词,您可以使用

val.match(/\b\d\w*/g)

请参见regex demoregex graph

enter image description here

详细信息

  • \b-单词边界
  • \d-一个数字
  • \w*-一个或多个字母,数字或下划线。

JavaScript演示

var val = "23_hell text 23 abc123 45_dell";
console.log( val.match(/\b\d\w*/g) );
// => ["23_hell", "23", "45_dell"]

答案 1 :(得分:0)

假设您的字符串使用逗号分隔每个单词,然后使用下面的示例:

var val = "23_hell,23,45_dell";
var newVal = val.split(","); // Returns ["23_hell","23","45_dell"]

并使用以下数据获取数据:

console.log(newVal[0]); // Logs first value (i.e. "23_hell");
console.log(newVal[1]); // Logs second value (i.e. "23");
console.log(newVal[2]); // Logs second value (i.e. "45_dell");