[英]javascript regex to find only numbers with hyphen from a string content
In Javascript, from a string like this, I am trying to extract only the number with a hyphen. 在Javascript中,我试图从这样的字符串中仅提取带有连字符的数字。 ie 67-64-1 and 35554-44-04.
即67-64-1和35554-44-04。 Sometimes there could be more hyphens.
有时可能会有更多的连字符。
The solvent 67-64-1 is not compatible with 35554-44-04
溶剂67-64-1与35554-44-04不兼容
I tried different regex but not able to get it correctly. 我尝试了其他正则表达式,但无法正确获取它。 For example, this regex gets only the first value.
例如,此正则表达式仅获取第一个值。
var msg = 'The solvent 67-64-1 is not compatible with 35554-44-04'; //var regex = /\\d+\\-?/; var regex = /(?:\\d*-\\d*-\\d*)/; var res = msg.match(regex); console.log(res);
You just need to add the g
(global) flag to your regex to match more than once in the string. 您只需要在正则表达式中添加
g
(全局)标志,即可在字符串中多次匹配。 Note that you should use \\d+
, not \\d*
, so that you don't match something like '3--4'. 请注意,您应该使用
\\d+
而不是\\d*
,以免与“ 3--4”之类的内容匹配。 To allow for processing numbers with more hyphens, we use a repeating -\\d+
group after the first \\d+
: 为了处理带有更多连字符的数字,我们在第一个
\\d+
之后使用重复的-\\d+
组:
var msg = 'The solvent 67-64-1 is not compatible with 23-35554-44-04 but is compatible with 1-23'; var regex = /\\d+(?:-\\d+)+/g; var res = msg.match(regex); console.log(res);
It gives only first because regex work for first element to test 它只给出第一个,因为正则表达式为第一个要测试的元素起作用
// g give globel access to find all
var regex = /(?:\d*-\d*-\d*)/g;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.