简体   繁体   中英

How to use Java Regex to put a particular string into array?

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?

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.

试试这个正则表达式......

(^\d|[\d]:|[\\s, *]+)+
String s = "1       2:no       2:no       0.002,*0.998";
String[] arr = s.split(" +");

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