如何否定包含范围的正则表达式?
How to negate regex expressions containing ranges?
我有以下正则表达式,用于标识字符串(符号数学方程式)中的索引变量名称:
[a-z][0-9]
我想删除字符串的所有 部分 而非 索引变量名称。我见过执行此操作的否定前瞻表达式,但我见过的示例使用锚点。如果这些示例包含变量名,它们将拒绝整个字符串,而不是替换字符串中不是变量名的部分。有没有一种有效的方法来完成这个?我正在使用 Java 的 replaceAll() 方法来尝试实现这个:
String s = "5x0 +3x2 = 7"; // I should get "x0 x2" after the regex
s.replaceAll("[a-z][0-9]", ""); // this should be negated
我很确定你想要的不能完成,但是可以完成并且更容易理解和编码的是:
Matcher m = Pattern.compile("[a-z][0-9]").matcher(s);
while (m.find()) {
String variable = m.group(); // do with it what you will
}
我有以下正则表达式,用于标识字符串(符号数学方程式)中的索引变量名称:
[a-z][0-9]
我想删除字符串的所有 部分 而非 索引变量名称。我见过执行此操作的否定前瞻表达式,但我见过的示例使用锚点。如果这些示例包含变量名,它们将拒绝整个字符串,而不是替换字符串中不是变量名的部分。有没有一种有效的方法来完成这个?我正在使用 Java 的 replaceAll() 方法来尝试实现这个:
String s = "5x0 +3x2 = 7"; // I should get "x0 x2" after the regex
s.replaceAll("[a-z][0-9]", ""); // this should be negated
我很确定你想要的不能完成,但是可以完成并且更容易理解和编码的是:
Matcher m = Pattern.compile("[a-z][0-9]").matcher(s);
while (m.find()) {
String variable = m.group(); // do with it what you will
}