简体   繁体   English

如何使用正则表达式匹配此字符串中的“ aas”?

[英]How can I use a regular expression to match “aas” in this string?

String str = "aa(aaq(aas)ppp)eeews";

How can I use a regular expression to match "aas" ? 如何使用正则表达式匹配"aas"

want to match the contents of the brackets, but not sure how many brackets,may be more and more 想匹配方括号中的内容,但不确定多少括号,可能会越来越多

(?<=\\()[^()]*(?=\\))
  • (?<=\\\\() - positive lookbehind to check for the existence of a opening bracket (?<=\\\\() -向后看以检查是否存在左括号
  • [^()] - a character, which is not a closing or opening bracket. [^()] -字符,不是右括号或右括号。 You don't want closing brackets so you don't match more than you need. 您不想用方括号括起来,所以您所匹配的内容不会超出您的需要。 You don't want opening brackets, because you wanted the inner most. 您不需要打开括号,因为您最想要的是内部。
  • * - repeat the above zero or more times * -重复以上零次或多次
  • (?=\\\\)) - positive lookahead to check for the existence of a closing bracket (?=\\\\)) -正向检查是否存在右括号

Since you need to match the text inside parentheses that has no ( or ) inside, you can use 由于您需要匹配括号内没有()的文本,因此可以使用

String str = "aa(aaq(aas)ppp)eeews";
String rx = "\\(([^()]*)\\)";
Pattern ptrn = Pattern.compile(rx);
Matcher m = ptrn.matcher(str);
while (m.find()) {
   System.out.println(m.group(1)); // => aas
}

See regex demo 正则表达式演示

The text you need is in Capture group 1. See IDEONE demo . 您需要的文本在Capture组1中。请参见IDEONE演示 To only get the first occurrence, use if instead of while . 要仅获得第一次出现,请使用if代替while

Another way to get the first occurrence is with "aa(aaq(aas)ppp)eeews".replaceAll("(?s).*?\\\\(([^()]*)\\\\).*$", "$1") ( demo ). 获得第一次出现的另一种方法是使用"aa(aaq(aas)ppp)eeews".replaceAll("(?s).*?\\\\(([^()]*)\\\\).*$", "$1")演示 )。

Why not use lookarounds? 为什么不使用环顾四周? You can, but they always involve some additional overhead to the regex engine. 您可以,但是它们总是会给正则表达式引擎带来一些额外的开销。 Certainly, with this basic pattern as here, performance is not the key, however, it is best practice to only use lookarounds when you have to. 当然,使用此处的基本模式,性能不是关键,但是,最佳实践是仅在需要时使用环顾四周。

The regex details: 正则表达式详细信息:

  • \\( - matches an opening ( \\( -匹配一个开头(
  • ([^()]*) - Capture group 1 matching zero or more characters other than ( or ) ([^()]*) -捕获匹配零个或多个(不是()字符的组1
  • \\) - matches closing round bracket. \\) -匹配右括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM