3

我有以下字符串“类(102)(401)”和“类(401)”我想找到正则表达式来查找子字符串,在我的情况下它总是返回最后一个括号值它是'(401)'

以下是我的代码

Pattern MY_PATTERN = Pattern.compile(".*(\\(\\d+\\))");
    Matcher mat = MY_PATTERN.matcher("Class (102) (401)");
    while (mat.find()){
        System.out.println(mat.group());
    }

它正在返回

--( --) --( --)

4

3 回答 3

2

您可以使用:

Pattern MY_PATTERN = Pattern.compile(".*(\\(\\d+\\))");

看见

于 2012-05-03T08:14:12.080 回答
1

试试这个:

(?<=\()[^\)(]+(?=\)[^\)\(]+$)

解释:

<!--
(?<=\()[^\)(]+(?=\)[^\)\(]+$)

Options: ^ and $ match at line breaks; free-spacing

Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\()»
   Match the character “(” literally «\(»
Match a single character NOT present in the list below «[^\)(]+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   A ) character «\)»
   The character “(” «(»
Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=\)[^\)\(]+$)»
   Match the character “)” literally «\)»
   Match a single character NOT present in the list below «[^\)\(]+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
      A ) character «\)»
      A ( character «\(»
   Assert position at the end of a line (at the end of the string or before a line break character) «$»
-->
于 2012-05-03T08:30:50.327 回答
1

表达方式如何:.*\\(([^\\(\\)]+)\\)[^\\(\\)]*$

它发现 a(后跟非括号[^\\(\\)](您想要的字符串),然后是 a ),之后只允许非括号,所以它必须是最后一个

于 2012-05-03T08:40:19.213 回答