[英]Regex Ignore if between certain characters
Say I have a string:假设我有一个字符串:
"ABC+DF" + someVar + exp(A+B)
I would like to match the + signs before and after some var and not match on ones in double quotes or inside an exp().我想在一些 var 之前和之后匹配 + 符号,而不是在双引号中或在 exp() 中匹配。
Is there a regex way to match only the + signs not in quotes or in the exp()?是否有正则表达式只匹配不在引号或 exp() 中的 + 符号?
Update:更新:
You can assume everything inside exp() should be ignored.您可以假设 exp() 中的所有内容都应该被忽略。 Maybe that is another way of thinking about it.也许这是另一种思考方式。 Anything in between quotes or exp() should be ignored from the regex.正则表达式中应忽略引号或 exp() 之间的任何内容。
Regex would be used in java String::split method.正则表达式将用于 java String::split 方法。 I am unsure about which platform that would be.我不确定这将是哪个平台。
You can use this in Java with replaceAll + split
operations:您可以在 Java 中使用replaceAll + split
操作:
jshell> String s = "\"ABC+DF\" + someVar + exp(A+B)";
s ==> "\"ABC+DF\" + someVar + exp(A+B)"
jshell> s.replaceAll("(\"[^\"]*\"|exp\\h*\\([^)]*\\))|\\h*\\+\\h*", "$1\0").split("\0+");
$15 ==> String[3] { "\"ABC+DF\"", "someVar", "exp(A+B)" }
replaceAll
matches and captures the part we want to ignore in group #1 on left hand side of alternation. replaceAll
中使用的正则表达式匹配并捕获我们想要在交替左侧的组 #1 中忽略的部分。 It then replaces match with $1\\0
where \\0
is a NUL byte (ASCII: 0).然后它用$1\\0
替换匹配,其中\\0
是一个 NUL 字节(ASCII:0)。split
just splits on one or more NUL bytes ie \\0
. split
使用的正则表达式只是拆分一个或多个 NUL 字节,即\\0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.