Created
September 4, 2017 20:45
-
-
Save claraj/d4f1eea2800f9d71e089e705880b6425 to your computer and use it in GitHub Desktop.
Regular expressions in Java
This file contains hidden or 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 REGEX { | |
public static void main(String[] args) { | |
// Get the text of the first match from a regex. | |
String testString = "There are 14 penguins sitting on 3 chairs"; | |
String regex = "\\d+"; //1 or more digits. Escape the special char \ | |
Pattern pattern = Pattern.compile(regex); | |
Matcher m = pattern.matcher(testString); | |
System.out.println(m.find()); // true | |
System.out.println(m.group()); // The text matched. Call .find() first | |
System.out.println(m.start()); // Start index of the previous match. Char 10 | |
System.out.println(m.end()); // End index of the previous match. Char 12 | |
System.out.println(m.find(15)); // Start looking at char 15. true | |
System.out.println(m.start()); // Start index of the previous match - now 32 | |
System.out.println(m.end()); // End index of the previous match - now 34 | |
System.out.println(m.matches()); // true if there's one+ matches | |
Matcher m2 = pattern.matcher("There are 12 penguins, 15 cats, 34 dogs, and 1 ferret."); | |
while ( m2.find()) { | |
System.out.println(m2.group()); // 12, 15, 24, 1 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment