How to use regular expressions in Java? For example, I have the string "5 * 6/9 + M5" I need to split the line into the lines "5", "6", "7", "M5". Used so

String value[] = val.split("[/][*][-][+]"); 

Somehow it did not work.

There is also such a way

 Pattern p = Pattern.compile("[/][*][-][+]"); Matcher m = p.matcher(value); 

But I do not understand what to do next. Help who can.

    2 answers 2

     [/][*][-][+] 

    matches the text:

     /*-+ 

    just like that - four characters one by one.
    I recommend reading the basics of regular expressions in terms of character classes.
    This will allow you to independently come to this solution to the problem:

     String[] value = val.split("[/*+-]"); 

      In the split pattern, it’s enough to write [/*+-] , that is, to find one any character represented in the set. And since the array should return, you need to add it not in the String value , but in the String[] value

       String testy = "5*6/999+M5"; String[] value = testy.split("[/*+-]"); for (String s : value) { System.out.println(s); } 

      will lead

       5 6 999 M5 

      http://ideone.com/gV5Zlq


      C Pattern / Matcher will be more complicated. The pattern itself will look something like this: [^/*+-]+ , that is, find characters 1 or more that are not / and not * and not + and not - ;

       String testy = "5*6/9+M5"; Pattern p = Pattern.compile("[^/*+-]+"); Matcher m = p.matcher(testy); 

      However, this is not enough. In order to find all these matches and where to stuff, you need to use the find() method - it returns true if the pattern matches any part of the text.

      After a successful match, m.start() returns the index of the first character that matched, and m.end() returns the index of the last matching character, plus one.

       while(m.find()) { System.out.println(testy.substring(m.start(), m.end())); } 

      http://ideone.com/HtxN8R

      You can add all this to some ArrayList or something else, at will.


      And depending on whether there are spaces between the numbers and the characters or something else, it will be necessary to correct the regulars.