So, how do we use it in Java ?
It's easy, just take a look at following tips.
Matching a text pattern within a String object
boolean java.lang.String.matches(String regex)
Example 1:
if(textToBeMatched.matches("[a-z A-Z]+"))
System.out.println("Text match with a series of alphabet and space character only pattern");
Example 2:
public class RegexTest {
public static void testPhoneNumber(String phoneNumber)
{
String phoneNumberPattern = "^\\+{0,1}[\\d]+[-\\d]+\\d$";
if(phoneNumber.matches(phoneNumberPattern))
System.out.println(phoneNumber + " is a correct phone number !");
else
System.out.println(phoneNumber + " is a wrong phone number !");
}
public static void main(String[] args)
{
testPhoneNumber("+6221-3011-9353"); //outputs a correct phone number
testPhoneNumber("-6221-3011-9353"); //outputs a wrong phone number
}
}
Replacing text that match a pattern
First, we initialize the pattern with compile() static method of Pattern class. With which also create a Pattern object. We then feed a source text to the matcher() method which then create a Matcher object. The last thing for us to do is to manipulate the text within the object, so we replace text with Matcher's replaceAll() method.
Example:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexReplacementTest {
public static String censoredPhoneNumber(String phoneNumber)
{
String phonePattern = "(\\+{0,1}[\\d]+[-\\d]+\\d).*";
Pattern pattern = Pattern.compile(phonePattern);
Matcher matcher = pattern.matcher(phoneNumber);
return matcher.replaceAll("*censored*");
}
public static void main(String[] args)
{
String phoneNo = "My phone number is +6221-3011-9353";
System.out.println(censoredPhoneNumber(phoneNo));
}
}
Conclusion
This blog's article show how we use regular expression in two ways :
- to match a text pattern using String's matches() method.
- to replace string which match a text pattern with two helper classes, Pattern and Matcher.
Hope this article can help you to resolve text manipulation problem that you may have encountered.
Any comments to improve this article is greatly welcomed. Post your comment here or mail to feris@phi-integration.com.