Playing with String is alot of fun in Java as it provide a host of String function. But as the String size increases the overhead increases. Suppose we are playing with some websites source code and we need to find the value of a particular tag in HTML. This type of situation we often face while programming as there is not a proper way to handle this by the String class methods.

This type of scenarios can be best handle with the help of Regular Expressions or Regex as popularly known. Regex can be a set of rules / pattern which when used smartly can yield fruitful results. Regex can be coupled with not just JAVA but with other programming languages as well without much difference as such.

We use Regex by creating a pattern and then matching our required String with that pattern.

String ourOriginalString = "our-string-comes-here";
String ourPattern = "our-pattern-comes-here";
Pattern pattern = Pattern.compile(ourPattern);
Matcher matcher = pattern.matcher(ourOriginalString);

while(matcher.find()){
     System.out.println(matcher.group(1));
}

Now we will continue with our search for Title in HTML code.

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexStringFinder {
  public static void main(String[] args) {
     String ourOriginalString = "<html><head><title>My Website!</title></head><body><h1>Hello World!</h1></body>";
     String ourPattern = "<title>(.*?)</title>";
     Pattern pattern = Pattern.compile("<title>(.*?)</title>");
     Matcher matcher = pattern.matcher(ourOriginalString);

      while(matcher.find()){
             System.out.println("Title: "+matcher.group(1));  
      }
  }
}

In This we need to import the Appropriate java.util packages.




Leave a Reply

Your email address will not be published. Required fields are marked *