[英]regex: get match and remaining string with regex
我想使用RegExp构造函数对字符串运行正则表达式,让我同时获得匹配项和剩余字符串。
以上是为了能够实现以下 UI 模式:
正如您在图像中看到的那样,我需要将匹配项与字符串的其余部分分开,以便能够单独应用某些样式或任何其他过程。
/**
* INPUT
*
* input: 'las vegas'
* pattern: 'las'
*
*
* EXPECTED OUTPUT
*
* match: 'las'
* remaining: 'vegas'
*/
获取匹配项,然后将匹配项替换为字符串中的任何内容,并返回两个结果。
function matchR(str, regex){
// get the match
var _match = str.match(regex);
// return the first match index, and the remaining string
return {match:_match[0], remaining:str.replace(_match, "")};
}
这是一个函数,它将用户输入和要匹配的字符串数组作为参数,并返回一个数组:
const strings = [ 'Las Cruces', 'Las Vegas', 'Los Altos', 'Los Gatos', ]; function getMatchAndRemaining(input, strings) { let escaped = input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); let regex = new RegExp('^(' + escaped + ')(.*)$', 'i'); return strings.map(str => { return (str.match(regex) || [str, '', str]).slice(1); }); } //tests: ['l', 'las', 'los', 'x'].forEach(input => { let matches = getMatchAndRemaining(input, strings); console.log(input, '=>', matches); });
一些注意事项:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.