[英]RegEx replacing numbers greater than variable in Javascript
我有字符串:“selection1 selection2 selection3 selection4”
我希望删除所有以大于变量的数字结尾的单词。 例如:
let str = "selection1 selection2 selection3 selection4";
let x = 2;
let regExp = RegExp(...);
let filtered = str.replace(regExp , ""); // should equal "selection1 selection2"
我想出了以下表达式,它选择所有以大于 29 的数字结尾的单词:
/(selection[3-9][0-9]|[1-9]\d{3}\d*)/gi
这个正则表达式在字符串“selection1 selection 40”上的结果是 [selection40]
我觉得我是那里的一部分。
鉴于我正在处理一位和两位数字并且希望合并一个变量,什么正则表达式可以帮助我改变这个字符串?
您可以将.replace
与回调一起使用:
let str = "selection5 selection1 selection2 selection3 selection4"; let x = 2; let regex = /\\s*\\b\\w+?(\\d+)\\b/g; let m; let repl = str.replace(regex, function($0, $1) { return ($1 > x ? "" : $0); }).trim(); console.log( repl );
正则表达式/\\b\\w+?(\\d+)\\b/g
匹配所有以 1+ 数字结尾的单词,并捕获捕获组 #1 中的数字,我们在回调函数中使用它来与变量x
进行比较。
您可以按空格拆分,然后使用 Regex捕获该组,它获取唯一的数字部分并相应地对其进行过滤。
const str = "selection1 selection2 selection3 selection4"; const threshold = 2; const pattern = /selection(\\d+)/ const result = str .split(' ') .filter(x => Number(x.match(pattern)[1]) <= threshold) .join(' '); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.