简体   繁体   English

Java模式匹配中提取括号之间的内容

[英]Java Pattern Matching in Extract content between parentheses

Need to extract content between parentheses for (20) - should return 20 for ("creamy") - should return creamy 需要在括号之间提取内容(20) -应该返回20 ("creamy") -应该返回creamy

I tried with the below pattern matcher but did not work. 我尝试了以下模式匹配器,但没有用。 Can someone help? 有人可以帮忙吗?

Pattern pattern = Pattern.compile("\\((.*?)\\)");

Did you encounter the compiler error on the single \\? 您是否在单个\\上遇到了编译器错误? For that to compile in Java, you need to escape the backslash otherwise the compiler tries to find the special character (. So it should be: 为了使用Java进行编译,您需要转义反斜杠,否则编译器将尝试查找特殊字符(。因此应为:

Pattern pattern = Pattern.compile("\\((.*?)\\)");
Matcher match = pattern.matcher("(cream)");
match.find();
System.out.println(match.group(1));

prints out 打印出来

cream

Try using regular expression in java. 尝试在Java中使用正则表达式。 See code snippet below. 请参见下面的代码段。

String matched = "";
Pattern pattern = Pattern.compile("\\((.*?)\\)");
Matcher matcher = pattern.matcher("(20)");
if (matcher.find()) {
   matched = matcher.group(1);
}
System.out.println(matched);

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

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