Search code examples
javapattern-matchingdesign-patternsmatcher

How do I use pattern and matcher to split a large string up into specific substrings in Java?


I've never done this before, but basically I'm trying to break a large string up into substrings (based on a regular expression) and then make use of those substrings one at a time. Can anyone show me the easiest way to do this? I just don't quite know how to use the methods of pattern and matcher.

Thanks!


Solution

  • java.lang.String.split() takes a regular expression and will split the string, returning a String[] containing the substrings:

    String s = "a:very:big:string";
    String[] parts = s.split(":");
    
    for (String part: parts)
    {
        System.out.println(part);
    }
    

    You don't need to use the Pattern and Matcher classes to achieve this.