Javascript Regex删除任何';它不是数字或特定的单词
因此,我有一个数学算法创建者,用户从可能的变量列表中插入变量,他们可以创建一个算法,只使用那些变量、数字和数学中使用的字符,如括号和其他。 我需要一个正则表达式,它将从字符串中删除不是这些变量之一或().-+/或数字的任何内容。 我尝试过很多正则表达式,但没有一个能满足我的需要 所有变量必须用花括号括起来 比如说Javascript Regex删除任何';它不是数字或特定的单词,javascript,regex,Javascript,Regex,因此,我有一个数学算法创建者,用户从可能的变量列表中插入变量,他们可以创建一个算法,只使用那些变量、数字和数学中使用的字符,如括号和其他。 我需要一个正则表达式,它将从字符串中删除不是这些变量之一或().-+/或数字的任何内容。 我尝试过很多正则表达式,但没有一个能满足我的需要 所有变量必须用花括号括起来 比如说 /^(?!{profitPercent}|{productPrice}|{weight}|{quantityInCart}|{lineTotal}|{cartTotal}|{billi
/^(?!{profitPercent}|{productPrice}|{weight}|{quantityInCart}|{lineTotal}|{cartTotal}|{billingUnits}|{test_111}|{test_213}|{test_prod_input_15}|{test_prod_input_16}).*/g
这只是删除了所有内容,数字和()也不例外*-+/
假设我有以下字符串:
var str='this is a string with a {productPrice} variable and some 827/100 math in it';
我需要把所有东西都拿走,除了
{productPrice}827/100
这是我的代码:
var reg=new RegExp("^(?!{" + escapeString(variableNames.join("}|{")) + "}).*","g");
txt=txt.replace(reg,'');
我尝试了许多不同的表达式,但没有一个有效。我将使用“匹配”来选择所需的值
{[^}]+}|[\d)(.*+/]+
-匹配{[^}]+}
,后跟任何{
}
-替换|
-匹配[[\d)(.*+/]+]
数字、运算符、(,)
let str=`var str='这是一个包含{productPrice}变量和827/100数学值的字符串`
设op=str.match(/{[^}]+}|[\d)(.*+/]+/g)
如果先拆分字符串,console.log(op.join(“”))
可能会更容易
const白名单=新集合([
“{profitPercent}”,
“{productPrice}”,
“{weight}”,
“{QuantityInvott}”,
“{lineTotal}”,
“{cartTotal}”,
“{billingUnits}”,
“{test_111}”,
“{test_213}”,
“{test_prod_input_15}”,
“{test_prod_input_16}”,
])
常量正则表达式=/[0-9.*\-+\/];
const str='这是一个包含{productPrice}变量和827/100数学值的字符串'
const newStr=str.split(“”).filter((word)=>{
返回白名单.has(word)| | regex.test(word)
}).加入(“”)
log(newStr)
可以这样做
/.*(?:(?:{profitPercent}{productPrice}}{weight}}{quantityinformat}}{lineTotal}{cartotal}{billingUnits}{test|111}{test|u213}{test test|uprodu input}{u15}{test produ input}}{16}/.[-]
不要删除你不想要的,而是删除除你想要的以外的所有内容。
积极的解释总是更好
替换为所需的$1
扩大
.*?
(?:
( # (1 start)
(?:
{profitPercent}
| {productPrice}
| {weight}
| {quantityInCart}
| {lineTotal}
| {cartTotal}
| {billingUnits}
| {test_111}
| {test_213}
| {test_prod_input_15}
| {test_prod_input_16}
| [-().*+\d/]
)+
) # (1 end)
|
$
)
您可以在非捕获组(?:
然后将要匹配的变量添加到字符类[().++/\d]++
,并将其添加到
这将为您提供要保留的匹配项,您可以使用空字符串作为分隔符来连接它们,从而产生:
{productPrice}827/100
您的代码(您必须添加escapeString
)可能如下所示:
var variableNames=[
“利润率”,
“产品价格”,
“重量”,
“数量化身”,
“lineTotal”,
“Cartotal”,
“比林格尼茨”,
“测试111”,
“测试213”,
“测试产品输入15”,
“测试产品输入16”
];
var str='这是一个带有{productPrice}变量和827/100数学的字符串';
var reg=new RegExp(“(?:{”+变量名称.join(“}|{”)+“}|[\\d)(.++]+),“g”);
str=str.match(reg.join)(“”);
console.log(str);
感谢这一点。我现在正试图使用preg_replace在php中应用相同的正则表达式来做与此相同的事情。我正在使用preg_replace('/(?:{).inpolde('}}}{',array_column($vars,'name')。}[d0-9'.preg_quote(inpolde(''.$chars))。\/]+/',''$algon);但它返回了我不想要的文本。我在这里做错了什么?@Suzannedelman您使用的是preg_replace,但我认为您可以使用preg_match_all,例如