简体   繁体   中英

How to split a string based on parenthesis and avoiding whitespace

I'm trying to reformat a string using the str.split() on string such as

"(ABD) (DEFG) (HIJKLMN)" (has one or more spaces between)

I've tried using this RegEx (Java)

[the example string] .split("\\(|\\)")

My output keeps including the "" or " " in my array from splitting, which I don't want I would want my array to be such that

array[0] = "ABC" array[1] = "DEFG" etc.

I would perform two steps, use String.replaceAll(String, String) to remove the () characters. Then, split on white-space. Like,

String str = "(ABD) (DEFG) (HIJKLMN)";
System.out.println(Arrays.toString(str.replaceAll("[()]", "").split("\\W+")));

which outputs (as requested)

[ABD, DEFG, HIJKLMN]

Alternatively, you could use an ArrayList and compile a reusable Pattern to perform a grouping operation on the contents of () literals. Like,

String str = "(ABD) (DEFG) (HIJKLMN)";
Pattern p = Pattern.compile("\\((\\w+)\\)");
Matcher m = p.matcher(str);
List<String> matches = new ArrayList<>();
while (m.find()) {
    matches.add(m.group(1));
}
System.out.println(matches);

which will continue to work in the face of input without white-space between () (s) like String str = "(ABD)(DEFG)(HIJKLMN)";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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