Showing posts with label Regex. Show all posts
Showing posts with label Regex. Show all posts

Monday, 25 April 2016

How to use methods of Matcher class ?


Find using Matcher
Pattern p = Pattern.compile("Java");
String candidateString = "I love Java2s. Java2s is about Java.";
Matcher matcher = p.matcher(candidateString);
while (matcher.find()) {
  System.out.print(" " + matcher.group());
}

Java Java Java

Case-insensitive flag can be used with pattern :
Pattern p = Pattern.compile("mice", Pattern.CASE_INSENSITIVE);


Reset Matcher
Pattern p = Pattern.compile("\\d");
Matcher m1 = p.matcher("01234");
while (m1.find()) {
  System.out.print(" " + m1.group());
}

m1.reset();
System.out.println("After resetting the Matcher");

while (m1.find()) {
  System.out.println(" " + m1.group());
}

0 1 2 3 4
After resetting the Matcher
0 1 2 3 4


Replace all
Pattern p = Pattern.compile("(i|I)ce");
// create the candidate String
String candidateString = "I love ice. Ice is my favorite. Ice Ice Ice.";
Matcher matcher = p.matcher(candidateString);
String tmp = matcher.replaceAll("Java");
System.out.println(tmp);

I love Java. Java is my favorite. Java Java Java.


Replace first occurance
Use replaceFirst instead of replaceAll method.
String tmp = matcher.replaceFirst("Java");

I love Java. Java is my favorite. Ice Ice Ice.


Find group
String regex = "(\\w+)(\\d\\d)(\\w+)";
Pattern pattern = Pattern.compile(regex);
String candidate = "X99SuperJava";
Matcher matcher = pattern.matcher(candidate);
matcher.find();
System.out.print(matcher.group(1));
System.out.print(matcher.group(2));
System.out.print(matcher.group(3));

X 99 SuperJava


Split
Pattern pattern = Pattern.compile("ing");
String candidate = "playingrowinglaughingsleepingweeping";
Matcher matcher = pattern.matcher(candidate);
String[] str = pattern.split(input, 4);
for(String st : str) {
  System.out.println(" " + st);
}

play row laugh sleepingweeping


Match with boolean result
String inputStr = "Computer";
String pattern = "Computer";
boolean patternMatched = Pattern.matches(pattern, inputStr);
System.out.println(patternMatched);

true

How to use group numbers with Matcher ?


Using group numbers with Macher

The whole pattern is defined to be group number 0.
Any capturing group in the pattern start indexing from 1.
The indices are defined by the order of the opening parentheses of the capturing groups.

EXAMPLE
Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+)

String: "!* UserName10 John Smith 01123 *!"

group(0): UserName10 John Smith 01123
group(1): UserName10
group(2):
group(3): John Smith
group(4):
group(5): 01123

There are 5 groups which are each enclosed in parentheses.
group(0) gives you the entire matched string.
groups 2 and 4 are simply the white space (space char / line feed / tab)

CODE
Pattern pattern=Pattern.compile("pattern");
Macher matcher=pattern.matcher("string");
if(matcher.matches()) {
  grp0 = matcher.group(0);
  grp1 = matcher.group(1);
  ...
}

Splitting a java String by the pipe symbol using String.split()


Just using pipe "|" inside split function will not work :
String test = "A|B|C||D";
String[] result = test.split("|");

You need to escape that special character using \\
String[] result = test.split("\\|");

Friday, 22 April 2016

Using different Regex operations



Example of Regex operations
* All examples below are having a pattern, matched strings in green and unmatched in red.


Concatenation
Simplest ; Concatenating a bunch of symbols together
aabaab 
aabaab 
every other string 

Logical OR (Alternation)
To choose from one of several possibilities
aa | baab 
aa
baab 
every other string 

Replication
To specify infinitely many possibilities ; Note : 0 replications of b are permitted.
ab*a 
aa
aba 
abba 
ab
ababa

Grouping
To specify precedence to the various operators 
The replication operator has the highest precedence, then concatenation, then logical OR.
a(a|b)aab 
aaaab
abaab 
every other string

Wildcard
It matches exactly one occurrence of any single character.
a..a 
abba
abaa 
aa
aaaaa 

One or more
a(bc)+de 
abcde
abcbcde 
ade
abc

Once or Not at all
a(bc)?de 
ade
abcde
abc
abcbcde

Character classes (Range)
[a-m]* 
blackmail
imbecile 
above
below

Negation of character classes (Range)
[^aeiou] 
b
c 
a
e

Exactly N times
[^aeiou]{6} 
rhythm
syzygy 
rhythms
allowed

Between M and N times
[a-z]{4,6} 
spider
tiger 
jellyfish
cow

Whitespace characters
[a-z\s]*hello 
hello
say hello 
Othello
2hello

How to use Pattern and Matcher classes ?


Pattern and Matcher classes

Compile a regular expression using regex expression
Pattern myPattern = Pattern.compile("regex");

Split the subject string using the compiled regular expression
myPattern.split("subject")
Exactly same result as : "subject".split("regex")  
but, faster since the regex was already compiled.

Create a Matcher object from the Pattern object
Matcher myMatcher = Pattern.matcher("subject")

* The advantage of having two separate classes is that you can create many Matcher objects from a single Pattern object, and thus apply the regular expression to many subject strings simultaneously.

Find the next matches of regex in the subject string
myMatcher.find()
The Matcher is automatically reset to the start of the string when find() fails.

Replace the matched string with new string
myMatcher.replaceAll("replacement")
Exactly same results as : "subject".replaceAll("regex", "replacement") 
but, faster due to pre-compilation.


Matching special characters
Backslash
In regex, the backslash is also an escape character. The regular expression \\ matches a single backslash.
"\\\\" will match single backslash. 
Here : \\ for regex and \\ for Java backslash symbol.

Word
Regex \w matches a word character. As a Java string, this is written as \\w.

Dollar sign
Same as this, a single dollar sign in the replacement text becomes "\\$" when written as a literal Java string.

What are the regex methods of the String class ?


Regex methods of the String class

myString.matches("regex")
It returns true or false, depending whether the string can be matched entirely by the regular expression.
String.matches() only returns true if the entire string can be matched.
If myString is abc then myString.matches("bc") returns false.

myString.replaceAll("regex", "replacement")
Replaces all regex matches inside the string with the replacement string you specified.
No surprises here. All parts of the string that match the regex are replaced.

myString.split("regex")
Splits the string at each regex match.
The method returns an array of strings where each element is a part of the original string between two regex matches.