Java正则表达式查找子字符串

3
我有以下字符串 "Class (102) (401)" 和 "Class (401)",我想要找到一个正则表达式,以查找子字符串并始终返回我的最后一个括号值,在我的情况下是'(401)'。
以下是我的代码。
Pattern MY_PATTERN = Pattern.compile(".*(\\(\\d+\\))");
    Matcher mat = MY_PATTERN.matcher("Class (102) (401)");
    while (mat.find()){
        System.out.println(mat.group());
    }

它返回了:

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


2
获取最后一个 ( 和 ) 的索引,然后获取两者之间的子字符串怎么样? - Chetter Hummin
3个回答

2

您可以使用:

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

点击这里查看


我尝试过并返回了“Class(102)(401)”,我只想要最后一个在括号中的值“401”。 - d-man
1
@Faisalkhan:你需要使用group(1)。请查看工作链接。 - codaddict
还有一个小帮助,如果我想要401而不是(401),那么需要做什么更改? - d-man
@Faisalkhan:使用模式:".*\\((\\d+)\\)" - codaddict

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) «$»
-->

1

这个表达式怎么样:.*\\(([^\\(\\)]+)\\)[^\\(\\)]*$

它可以找到一个(后面跟着非括号字符[^\\(\\)](你想要的字符串),然后是一个),之后只允许出现非括号字符,所以它必须是最后一个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接