[英]Match a regular expression, then remove a subset of that regular expression
I'm using javascript to parse through some strings. 我正在使用javascript解析一些字符串。
I have some strings that look like this: 我有一些看起来像这样的字符串:
1234 1/2 Old Town Alexandria
I have written a regular expression to identify instances in which a fraction comes after the street number: 我写了一个正则表达式来标识实例,其中实例在街道号之后:
var addressFractionRegex = /^\d*\s+(1[/]\d)\s+/i;
What I would like to do is remove the fraction part of the regular expression from the source string only in cases where the entire regular expression is matched (ie: the fraction is preceded by a street number). 我想做的是仅在整个正则表达式都匹配的情况下才从源字符串中删除正则表达式的小数部分(即:小数前面带有街道编号)。 In this case, I would end up with (removing the "1/2"):
在这种情况下,我最终将(删除“ 1/2”):
1234 Old Town Alexandria
I would also like to save the part that I removed into another variable. 我还想将删除的部分保存到另一个变量中。 So ideally, I'd end up with something like:
因此,理想情况下,我最终会得到以下结果:
var street_address = '1234 Old Town Alexandria';
var fraction = '1/2';
How is this done in javascript? 如何在javascript中完成?
Thanks! 谢谢!
replace can take a function : 替换可以带一个功能 :
var fraction;
var street_address = "1234 1/2 Old Town Alexandria".replace(/^\d*\s+(1[/]\d)\s+/i, function (match, capture) {
fraction = capture.trim();
return match.replace(capture,'')
});
fraction; // 1/2
street_address; // 1234 Old Town Alexndria
The replace
function takes a replacement string. replace
函数接受一个替换字符串。 You can group everything you want to keep, and omit anything you want to take out. 您可以将要保留的所有内容归为一组,并忽略要取出的任何内容。 Here we keep subpatterns 1 and 3, and leave out your fraction stored in 2.
在这里,我们保留子模式1和3,并保留存储在2中的分数。
var addressFractionRegex = /^(\d*\s+)(1[/]\d)(\s+)/i;
var data = '123 1/5 abc';
alert(data.replace(addressFractionRegex, '$1$3'));
您只能捕获要保留的位:
"1234 1/2 Old Town Alexandria".replace(/^(\d*\s+)1\/\d\s/, '$1');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.