Regular expression for letters or numbers in brackets

I use Java to process text using regular expressions. I use the following regex

^[\([0-9a-zA-Z]+\)\s]+

to combine one or more letters or numbers in parentheses one or more times. For example, I like to match (aaa) (bb) (11) (AA) (iv) or (111) (aaaa) (i) (V)

I checked this regex at http://java-regex-tester.appspot.com/ and it works. But when I use it in my code, the code does not compile. Here is my code:

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class Tester {

        public static void main(String[] args) {

            Pattern pattern = Pattern.compile("^[\([0-9a-zA-Z]+\)\s]+");

            String[] words = pattern.split("(a) (1) (c) (xii) (A) (12) (ii)");

            String w = pattern.

            for(String s:words){

                System.out.println(s);

            }
    }
}

I tried to use \ instead of \, but the regular expression gave different results than expected (it corresponds to only one group, for example (aaa), and not to several groups, such as (aaa) (111) (ii).

Two questions:

  • ?
  • (, (aaa), (111) ..). pattern.split, .
+4
3

/ ,

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tester {
    static ArrayList<String> listOfEnums;
    public static void main(String[] args) {
        listOfEnums = new ArrayList<String>();
        Pattern pattern = Pattern.compile("^\\([0-9a-zA-Z^]+\\)");
        String p = "(a) (1) (c) (xii) (A) (12) (ii) and the good news (1)";
        Matcher matcher = pattern.matcher(p);
        boolean isMatch = matcher.find();
        int index = 0;
        //once you find a match, remove it and store it in the arrayList. 
        while (isMatch) {
          String s = matcher.group();
          System.out.println(s);
          //Store it in an array
          listOfEnums.add(s);
          //Remove it from the beginning of the string.
          p = p.substring(listOfEnums.get(index).length(), p.length()).trim();
          matcher = pattern.matcher(p);
          isMatch = matcher.find();
          index++;
        }
    }
}
+2

-, . . (, \w ..)

-, , :

String w = pattern.

, .

+7

1) . / , .

(abc) (def) (123)

, .

, ,

\([0-9a-zA-Z^\)]+\)

2) Java ,

3) split() , . , , . matcher()

Pattern pattern = Pattern.compile("\\([0-9a-zA-Z^\\)]+\\)");
Matcher matcher = pattern.matcher("(a) (1) (c) (xii) (A) (12) (ii)");

while (matcher.find()) {
  System.out.println(matcher.group());
}
0
source

Source: https://habr.com/ru/post/1524157/


All Articles