Reputation: 2291
How can I put the "no", "no", "0.002", "0.998" below into the String array with regex in Java?
String lines = " 1 2:no 2:no 0.002,*0.998"
Could someone please tell me how to write "theRegex" below?
String[] matches = lines.split(theRegex); // => ["no", "no", "0.002", "0.998"]
In Python, it will be just one line:
matches = line =~ /\d:(\w+).*\d:(\w+).*\((\w+)\)/
But how about Java?
Upvotes: 1
Views: 166
Reputation: 12398
theRegex="[\\s,*]+"
(one or more spaces, commas or asterisk)
Input 1 2:no 2:no 0.002,*0.998
Output ["1","2:no","2:no","0.002","0.9"]
Edit
The input String is " 1 2:no 2:no 0.002,*0.998", and the expected output is ["no", "no", "0.002", "0.998"]
In that case it is not possible to use split
alone, because for ignoring 1
you need to treat \d
as a delimiter, but \d
is also part of the data in 0.002
.
What you can do is:
Pattern pattern = Pattern.compile("^\\d(?:$|:)");
String[] matches = lines.trim().split("[\\s,*]+");
List<String> output = new LinkedList<String>(Arrays.asList(matches));
for (Iterator<String> it=output.iterator(); it.hasNext();) {
if (Pattern.matcher(it.next()).find()) it.remove();
}
find("^\\d(?:$|:")
matches strings of the form digit
or digit:whatever
. Note that the pattern is compiled once, then it is applied to the strings in the list. For each string one has to construct a matcher.
Upvotes: 2
Reputation: 12843
String s = "1 2:no 2:no 0.002,*0.998";
String[] arr = s.split(" +");
Upvotes: 0