Reputation: 153
How can i separate a string of (?abcd.efgdf)?
What i want to get is the "?abcd" and the "efgdf" being separate and transferred to another string container.
I know the use of split(".") , but what if there are two string like this. ex. (?abcd.efgdf) (?xcv.qwer) splitting the second string contains the end of 1st string which is "efgdf". so using split(".") is not an option.
Is there any kind of implementation of separating this string?
Upvotes: 1
Views: 196
Reputation: 4553
You should have a look at java.util.Pattern which will help you parse the whole string for those patterns you are looking for.
Pattern p = Pattern.compile("\((\?\w*)\.(\w*)\)");
Matcher m = p.matcher("(?abcd.efgdf) (?xcv.qwer)");
while (m.find()) {
list1.add(m.group(1));
list2.add(m.group(2));
}
Regular expressions might seem intimidating at first, but are well worth it for more complex cases. Read through the JavaDoc of Pattern to understand the possiblities. They will help in your example as they will get rid of all the spaces and brackets for you, so you only eal with what you are looking for, not what is in between. Furthermore, this works for strings containing any number of those (?abcd.abcd)
groups.
Upvotes: 0
Reputation: 31901
You can use Regex \(|\.|\)\s*\(|\)\??
.
It includes all of these delimiters:
(
first opening bracket.
a period)\s*(
optional whitespaces between brackets.)
closing bracket?
optional question mark following point #4
.But it may create some empty strings so using java 8 streams, you can remove them. Here's the code
Test case 1
String s = "(?abcd.efgdf)?";
String[] arr = Arrays.asList(s.split("\\(|\\.|\\)\\s*\\(|\\)\\??")).stream().filter(str -> !str.isEmpty()).collect(Collectors.toList()).toArray(new String[0]);
for (String a: arr) System.out.println(a);
Output
?abcd
efgdf
Test case 2
String s = "(?abcd.efgdf) (?xcv.qwer)";
String[] arr = Arrays.asList(s.split("\\(|\\.|\\)\\s*\\(|\\)\\??")).stream().filter(str -> !str.isEmpty()).collect(Collectors.toList()).toArray(new String[0]);
for (String a: arr) System.out.println(a);
Ouput
?abcd
efgdf
?xcv
qwer
Upvotes: 1
Reputation: 60046
You can split your String
with two delimiters with point
and with space
like this :
String [] spl = "(?abcd.efgdf) (?xcv.qwer)".split("\\.| ");
//---------------------------------------------------^-^--
So you will get :
(?abcd
efgdf)
(?xcv
qwer)
If your str = "(?abcd.efgdf)"
you will get :
(?abcd
efgdf)
Upvotes: 0