简体   繁体   English

Java检索括号中的字符串字符

[英]Java retrieve String characters in brackets

I have a String in Java that holds data in this format: 我在Java中有一个String,它以这种格式保存数据:

String x = "xxxxxx xxxxxx xxxxxx (xxx)";

How can I set the value of that string to just be the characters in the brackets, without including the brackets? 如何将字符串的值设置为方括号中的字符,而不包括方括号? (Note that the character sizes will vary in each instance). (请注意,字符大小在每种情况下都会有所不同)。

The one-line solution is to use String.replaceAll() and the appropriate regex that captures the whole input (effectively replacing the whole input), but also captures (non-greedily) the part you want as group 1, then puts back just that group: 单行解决方案是使用String.replaceAll()和适当的正则表达式来捕获整个输入(有效地替换整个输入),而且还捕获(非贪婪地)您要作为组1的部分,然后仅放回该组:

String part = x.replaceAll(".*\\((.*?)\\).*", "$1"); 

FYI, the double back-slashes in the regex String is a single slash in regex, which then escapes the literal brackets in the regex 仅供参考,正则表达式字符串中的双反斜杠是正则表达式中的单斜杠,然后转义正则表达式中的文字括号

Here's some test code: 这是一些测试代码:

public static void main(String[] args) {
    String x = "xxxxxx xxxxxx xxxxxx (xxx)";
    String part = x.replaceAll(".*\\((.*)\\).*", "$1");
    System.out.println(part);
}

Output: 输出:

xxx    

A regex will do that, but my regex-fu is weak. 正则表达式可以做到这一点,但是我的正则表达式很弱。 The non-regex way is as follows: 非正则表达式的方式如下:

int firstIndex = x.indexOf("(");
x = x.substring(firstIndex+1, x.length()-1);

EDIT: As pointed out in comments, if there are any other parentheses in the data, other than at the end, this will NOT work. 编辑:正如注释中指出的那样,如果数据中有其他任何括号(除了结尾处),则将不起作用。 You'd need to use the following instead: 您需要改用以下内容:

int firstIndex = x.lastIndexOf("(", x.length()-6);
x = x.substring(firstIndex+1, x.length()-1);

EDIT2: Just reread and realised that the close paren is the last character. EDIT2:重新阅读并意识到封闭括号是最后一个字符。 So there's no need to get the second index. 因此,无需获取第二个索引。

You can use String.split method for this kind of extraction.. 您可以使用String.split方法进行这种提取。

String x = "xxxxxx xxxxxx xxxxxx (xxx)";    
String[] arr = x.split("\\(");

x = arr[1].substring(0, arr[1].indexOf(")")); // To remove the trailing bracket.

System.out.println(x);

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

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