A regular expression is a sequence of predefined symbols specified in a predefined syntax that helps you search or manipulate strings.
Regex Support in Java
Java 1.4 SDK introduced regex support in Java. The package java.util.regex supports regex. It consists of two important classes, Pattern and Matcher.
Pattern represents a regex in a compiled representation, and Matcher interprets a regex and matches the corresponding substring in a given string.
Searching and Parsing with regex
Regex1.java
package com.appfworks.regex;
/**
* Created by suresh on 29/10/15.
*/
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex1 {
public static void main(String[] args) {
String str = "Danny Doo, Flat no 502, Big Apartment, Wide Road, Near Huge Milestone, " +
"Hugo-city 56010, Ph: 9876543210, Email: danny@myworld.com. Maggi Myer, Post bag no 52, Big bank post " +
"office, Big bank city 56000, ph: 9876501234, Email: maggi07@myuniverse.com.";
Pattern pattern = Pattern.compile("\\w+");
Matcher matcher = pattern.matcher(str);
while(matcher.find()) {
System.out.println(matcher.group());
}
// you can search all the numbers using the "\d+" regex
Pattern pattern2 = Pattern.compile("\\d{5}");
Matcher matcher2 = pattern2.matcher(str);
while(matcher2.find()) {
System.out.println(matcher2.group());
}
// This time you used "\D\d{5}\D" and it worked well. What you essentially did was specify that a non-digit
// character is preceded and followed by a six-digit number.
Pattern pattern3 = Pattern.compile("\\D\\d{5}\\D");
Matcher matcher3 = pattern3.matcher(str);
while(matcher3.find()) {
System.out.println(matcher3.group());
}
// you can use "\b" (used to detect word boundaries) here.
Pattern pattern4 = Pattern.compile("\\b\\d{5}\\b");
Matcher matcher4 = pattern4.matcher(str);
while(matcher4.find()) {
System.out.println(matcher4.group());
}
// In an e-mail address, the first partis a word (which can be specified by "\w+"),
// followed by a "@", followed by another word, and suffixed by ".com"
Pattern pattern5 = Pattern.compile("\\w+@\\w+\\.com");
Matcher matcher5 = pattern5.matcher(str);
while(matcher5.find()) {
System.out.println(matcher5.group());
}
}
}
No comments:
Post a Comment