GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing regexone.com — RegexOne - Learn Regular Expressions - Java All Lessons
Lesson 1: An Introduction, and the ABCs
Lesson 1½: The 123s
Lesson 2: The Dot
Lesson 3: Matching specific characters
Lesson 4: Excluding specific characters
Lesson 5: Character ranges
Lesson 6: Catching some zzz's
Lesson 7: Mr. Kleene, Mr. Kleene
Lesson 8: Characters optional
Lesson 9: All this whitespace
Lesson 10: Starting and ending
Lesson 11: Match groups
Lesson 12: Nested groups
Lesson 13: More group work
Lesson 14: It's all conditional
Lesson 15: Other special characters
Lesson X: Infinity and beyond!
Practice Problems
Problem 1: Matching a decimal numbers
Problem 2: Matching phone numbers
Problem 3: Matching emails
Problem 4: Matching HTML
Problem 5: Matching specific filenames
Problem 6: Trimming whitespace from start and end of line
Problem 7: Extracting information from a log file
Problem 8: Parsing and extracting data from a URL
Problem X: Infinity and beyond!
Using Regular Expressions in Java
If you need a refresher on how Regular Expressions work, check out our Interactive Tutorial first! Java supports regular expressions through the classes in the In the examples below, be sure to import the following package at the top of the source file if you are trying out the code: import java.util.regex.*;
Regular expression String patternsIn Java, regular strings can contain special characters (also known as escape sequences)
which are characters that are preceeded by a backslash ( For example, take the pattern This is only necessary when hard-coding patterns into Java code, as strings that are read in from user
input or from files are read by character individually and escape sequences are not interpreted. This is
a common approach to get around this problem, by either putting the patterns in a Other languages like C# or Python support the notion of raw strings, but Java has yet to add this useful feature into the core language. Matching a stringWorking with regular expressions in Java generally involves instantiating a Method
boolean isMatch = Pattern.matches(String regex, String inputStr)
However, this does not give you any additional information such as where in the input string the
pattern matches, or the groups that matched. So for most purposes, it is both more useful and also
more efficient to compile a new Methods
Pattern ptrn = Pattern.compile(String regex)
Matcher matcher = ptrn.matcher(String inputStr)
Example
// Lets use a regular expression to match a date string.
Pattern ptrn = Pattern.compile("([a-zA-Z]+) (\\d+)");
Matcher matcher = ptrn.matcher("June 24");
if (matcher.matches()) {
// Indeed, the expression "([a-zA-Z]+) (\d+)" matches the date string
// To get the indices of the match, you can read the Matcher object's
// start and end values.
// This will print [0, 7], since it matches at the beginning and end of the
// string
System.out.println("Match at index [" + matcher.start() +
", " + matcher.end() + ")");
// To get the fully matched text, you can read the Matcher object's group
// This will print "June 24"
System.out.println("Match: " + matcher.group());
}
Capturing groupsCapturing groups in a regular expression is as straightforward as matching a string in the example
above. After using a Example
// Lets use a regular expression to capture data from a few date strings.
String pattern = "([a-zA-Z]+) (\\d+)";
Pattern ptrn = Pattern.compile("([a-zA-Z]+) (\\d+)");
Matcher matcher = ptrn.matcher("June 24, August 9, Dec 12");
// This will print each of the matches and the index in the input string
// where the match was found:
// June 24 at index [0, 7)
// August 9 at index [9, 17)
// Dec 12 at index [19, 25)
while (matcher.find()) {
System.out.println(String.format("Match: %s at index [%d, %d]",
matcher.group(), matcher.start(), matcher.end()));
}
// If we are iterating over the groups in the match again, first reset the
// matcher to start at the beginning of the input string.
matcher.reset();
// For each match, we can extract the captured information by reading the
// captured groups.
while (matcher.find()) {
// This will print the number of captured groups in this match
System.out.println(String.format("%d groups captured",
matcher.groupCount()));
// This will print the month and day of each match. Remember that the
// first group is always the whole matched text, so the month starts at
// index 1 instead.
System.out.println("Month: " + matcher.group(1) + ", Day: " +
matcher.group(2));
// Each group in the match also has a start and end index, which is the
// index in the input string that the group was found.
System.out.println(String.format("Month found at[%d, %d)",
matcher.start(1), matcher.end(1)));
}
Finding and replacing stringsAnother common task is to find and replace a part of a string using regular expressions, for example,
to replace all instances of an old email domain, or to swap the order of some text. You can do this
in Java with the The replacement string can contain references to captured groups in the pattern (using the dollar sign $), or just a regular literal string. Method
String replacedString = matcher.replaceAll(String inputStr)
Example
// Lets try and reverse the order of the day and month in a few date
// strings. Notice how the replacement string also contains metacharacters
// (the back references to the captured groups) so we use a verbatim
// string for that as well.
Pattern ptrn = Pattern.compile("([a-zA-Z]+) (\\d+)");
Matcher matcher = ptrn.matcher("June 24, August 9, Dec 12");
// This will reorder the string inline and print:
// 24 of June, 9 of August, 12 of Dec
// Remember that the first group is always the full matched text, so the
// month and day indices start from 1 instead of zero.
String replacedString = matcher.replaceAll("$2 of $1");
System.out.println(replacedString);
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |