正则表达式在操作中获取字符串
Regex to obtain strings in operations
我需要使用带有 javascript 的正则表达式获取操作中涉及的元素。我知道这些字符串仅限于包含小写 a-z 字符、点、下划线字符和数字。我不需要抓住它们周围的元素,例如括号或 division/multiplication 符号。根据经验,我知道所有这些元素至少包含一个点。例如:
对于((my.metric.name_a-bc.test.metric)/(1000000-foo.bar.ab_cd))*100
,应该returnmy.metric.name_a-bc.test.metric
和1000000-foo.bar.ab_cd
对于100*another.metric.name.here
它应该returnanother.metric.name.here
对于 this * -1
它不应该 return 任何东西因为 none 的元素包含一个点。
谢谢!
如果您确定所有字符串都有效,您可以使用类似这样的方法:
const strings = [
'((my.metric.name_a-bc.test.metric)/(1000000-foo.bar.ab_cd))*100',
'100*another.metric.name.here',
'this * -1'
];
const values = strings.flatMap((str) => str.match(/(?:[\w-]+\.)+[\w-]+/ig))
我需要使用带有 javascript 的正则表达式获取操作中涉及的元素。我知道这些字符串仅限于包含小写 a-z 字符、点、下划线字符和数字。我不需要抓住它们周围的元素,例如括号或 division/multiplication 符号。根据经验,我知道所有这些元素至少包含一个点。例如:
对于
((my.metric.name_a-bc.test.metric)/(1000000-foo.bar.ab_cd))*100
,应该returnmy.metric.name_a-bc.test.metric
和1000000-foo.bar.ab_cd
对于
100*another.metric.name.here
它应该returnanother.metric.name.here
对于
this * -1
它不应该 return 任何东西因为 none 的元素包含一个点。
谢谢!
如果您确定所有字符串都有效,您可以使用类似这样的方法:
const strings = [
'((my.metric.name_a-bc.test.metric)/(1000000-foo.bar.ab_cd))*100',
'100*another.metric.name.here',
'this * -1'
];
const values = strings.flatMap((str) => str.match(/(?:[\w-]+\.)+[\w-]+/ig))