问题描述
以下 ,我这样做:
console.log(lines[line]);
var regex = /(-?\d{1,})/g;
var cluster = lines[line].match(regex);
console.log(cluster);
这将给我这个:
((3158), (737))
["3158", "737"]
其中3158将被视为我程序中的ID,737则被视为相关数据。
where 3158 will be latter treated as the ID in my program and 737 the associated data.
我想知道是否有处理此类输入的方法:
I am wondering if there was a way to treat inputs of this kind too:
((3158, 1024), (737))
其中ID是一对,并执行以下操作:
where the ID will be a pair, and do something like this:
var single_regex = regex_for_single_ID;
var pair_regex = regex_for_pair_ID;
if(single_regex)
// do my logic
else if(pair_regex)
// do my other logic
else
// bad input
这可能吗?
澄清:
我感兴趣的是以不同方式对待这两种情况。例如,一种解决方案就是有这种行为:
What I am interested in is treating the two cases differently. For example one solution would be to have this behavior:
((3158), (737))
["3158", "737"]
和对,连接ID :
((3158, 1024), (737))
["31581024", "737"]
推荐答案
简单来说,你可以使用 .replace(/(\d +)\ * *,\ s * / g,'$ 1')
合并/连接数字对,然后使用简单的正则表达式匹配已经在使用。
For a simple way, you can use .replace(/(\d+)\s*,\s*/g, '$1')
to merge/concatenate numbers in pair and then use simple regex match that you are already using.
示例:
var v1 = "((3158), (737))"; // singular string
var v2 = "((3158, 1024), (737))"; // paired number string
var arr1 = v1.replace(/(\d+)\s*,\s*/g, '$1').match(/-?\d+/g)
//=> ["3158", "737"]
var arr2 = v2.replace(/(\d+)\s*,\s*/g, '$1').match(/-?\d+/g)
//=> ["31581024", "737"]
我们在中使用此正则表达式。替换
:
/(\d+)\s*,\s*/
- 它匹配并分组1个或更多个数字,后跟可选空格和逗号。
- 在替换中,我们使用
$ 1
这是我们匹配的数字的后向引用,因此删除了数字后的空格和逗号。 - It matches and groups 1 or more digits followed by optional spaces and comma.
- In replacement we use
$1
that is the back reference to the number we matched, thus removing spaces and comma after the number.
这篇关于智能正则表达式来理解输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!