import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "\\d{3}-\\d{4}";
final String string = "[Verse 1]\n"
+ "Jenny, Jenny, who can I turn to?\n"
+ "You give me somethin' I can hold on to\n"
+ "I know you think I'm like the others before\n"
+ "Who saw your name and number on the wall\n\n"
+ "[Chorus 1]\n"
+ "Jenny, I got your number\n"
+ "I need to make you mine\n"
+ "Jenny, don't change your number\n\n"
+ "[Post-Chorus]\n"
+ "867-5309\n"
+ "867-5309\n"
+ "867-5309\n"
+ "867-5309\n\n"
+ "[Verse 2]\n"
+ "Jenny, Jenny, you're the girl for me\n"
+ "Oh, you don't know me, but you make me so happy\n"
+ "I tried to call you before, but I lost my nerve\n"
+ "I tried my imagination, but I was disturbed\n\n"
+ "[Chorus 1]\n"
+ "Jenny, I got your number\n"
+ "I need to make you mine\n"
+ "Jenny, don't change your number\n\n"
+ "[Post-Chorus]\n"
+ "867-5309\n"
+ "867-5309\n"
+ "867-5309\n"
+ "867-5309\n\n"
+ "[Bridge]\n"
+ "I got it, (I got it), I got it\n"
+ "I got your number on the wall\n"
+ "I got it, (I got it), I got it\n"
+ "For a good time, for a good time call\n\n"
+ "[Chorus 2]\n"
+ "Jenny, don't change your number\n"
+ "I need to make you mine\n"
+ "Jenny, I call your number\n\n"
+ "[Post-Chorus]\n"
+ "867-5309\n"
+ "867-5309\n"
+ "867-5309\n"
+ "867-5309\n\n"
+ "[Breakdown]\n"
+ "Jenny, Jenny, who can I turn to?\n"
+ "867-5309\n"
+ "For the price of a dime I can always turn to you\n"
+ "867-5309\n\n"
+ "[Outro]\n"
+ "867-5309\n"
+ "867-5309\n"
+ "867-5309\n"
+ "867-5309\n"
+ "5309\n"
+ "867-5309 (5309)\n"
+ "867-5309 (5309)\n"
+ "867-5309";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html