Skip to content

Instantly share code, notes, and snippets.

@tyrcho
Created April 19, 2018 21:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyrcho/ca796f921481adb4ed97c9c4cbba1e21 to your computer and use it in GitHub Desktop.
Save tyrcho/ca796f921481adb4ed97c9c4cbba1e21 to your computer and use it in GitHub Desktop.
free-spacing regex demo in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DemoFreeSpacingRegex {
public static void main(String[] args) {
String re = "(?x)\n"
+ "# ?x is free-spacing flag to allow #comments, must be right at start of String\n"
+ "(19|20\\d\\d) # year (group 1)\n"
+ "[- /.] # separator\n"
+ "(0[1-9]|1[012]) # month (group 2)\n"
+ "[- /.] # separator\n"
+ "(0[1-9]|[12][0-9]|3[01]) # day (group 3)";
Pattern pattern = Pattern.compile(re);
final Matcher matcher = pattern.matcher("2018-04-11");
final boolean found = matcher.find();
if (found) {
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println(matcher.group(i));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment