Regular expression (regex or regexp) is used for searching
using String pattern matching. Regex is a sequence of characters that forms a
search pattern .
JDK comes up with built-in api for regex manipulation.Regex can be implemented using the “Pattern” and the “Matcher”
class.
Sample program:
public static void main(String args[])
{
boolean gotit = false;
//
-------------------------------------
String line = "Rubesh is a
technology (XYZ technology solutions) !. mail - samson@gmail.com mobile -
754-543-5843";
String pattern = "[^a-z]";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher matcher = r.matcher(line);
while (matcher.find()) {
System.out.print(matcher.group());
gotit = true;
}
if(!gotit){
System.out.println("No results
!!!");
}
}
If you want to get the start & end index of a
selected letter in the output you can use the matcher.start() and
matcher.end().
Input / output samples:
Regex pattern Output
[a-z] ubeshisatechnologytechnologysolutionsmailsamsongmailcommobile
[A-Z] RXYZ
[A-Za-z] RubeshisatechnologyXYZtechnologysolutionsmailsamsongmailcommobile
[a-z0-9_-] ubeshisatechnologytechnologysolutionsmail-samsongmailcommobile-754-543-5843
[a-z0-9_-]{4,10} ubeshtechnologytechnologysolutionsmailsamsongmailmobile754-543-58
You can try out regex directly using www.regexpal.com
No comments:
Post a Comment