如何对字符串中的单个字符使用正则表达式?

How to use regex for a single character in a String?

我有以下字符串:

LoopStep(i,0,m-1,1) 

我想使用正则表达式,这样我就可以找到第一个“(”,例如我的正则表达式代码是:\([^)]*\)。我只想检查第一个左括号,这样我就不会这段代码没有问题:

LoopStep ((i,0,m-1,1)).

你可以使用问号。如果将它添加到正则表达式中,它就变成了非贪婪的。例如,模式“(”将匹配所有开括号,同时“(?”将只匹配第一次出现。

如果你只想检查你的String是否不包含两个连续的括号,你可以使用indexOfcontains 而不是正则表达式:

// will return true only if the String doesn't contain ((
// you can also use to infer actual index
test.indexOf("((") == -1
// same and better but you can't use the index
!test.contains("((")

请注意,此处 test 是您想要的 String 变量,例如值为 "LoopStep(i,0,m-1,1)".

如果您实际上是在解析语法(看起来确实如此),请不要使用正则表达式。

您可能必须构建自己的解析器才能验证和解析您的元语言的语法。

备注

如果您在这种情况下使用正则表达式来验证语法,只是为了让您了解可能会遇到什么麻烦,这里有一个正则表达式示例匹配您的整个 String 以检查连续的括号 ( "(("):

//           | non-parenthesis
//           |    | or
//           |    | | not preceded by parenthesis
//           |    | |      | actual parenthesis
//           |    | |      |  | not followed by parenthesis
//           |    | |      |  |       | 1+ length(adjust with desired quantifier)
test.matches("([^(]|(?<!\()\((?!=\())+")