Created
April 19, 2018 21:56
-
-
Save tyrcho/ca796f921481adb4ed97c9c4cbba1e21 to your computer and use it in GitHub Desktop.
free-spacing regex demo in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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