我有一个字符串:"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字符串“regEx selection40”上的这个selection1的结果是selection40
我觉得我是实现目标的一部分。
考虑到我正在处理单数和两位数的数字,并且希望合并一个变量,什么regEx可以帮助我改变这个字符串?
发布于 2019-04-19 14:56:00
您可以在回调中使用.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 );
Regex /\b\w+?(\d+)\b/g匹配以1+数字结尾的所有单词,并捕获捕获组#1中的数字,我们在回调函数中使用这些数字来与变量x进行比较。
发布于 2019-04-19 14:57:28
您可以按空格拆分,然后捕获组 使用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);
https://stackoverflow.com/questions/55763536
复制相似问题