Today's Question:  What are you most afraid of as a programmer?        GIVE A SHOUT

Technical Article => Programming =>  Programming

The Greatest Regex Trick Ever (Simplified)

  sonic0002      2015-10-01 21:59:05      1,294    0

There is a post which is really hot recently which showcased a best ever regular expression trick. In this post, it provides a trick which can be adapted to situations where one wants to match some patterns desired and exclude the patterns undesired. In simple, the trick is :

Pattern not desired | (Pattern desired)

Then taking the group 1 match of the capturing group of matched. This group will contain the strings matching the desired patterns.

Have to say this trick is really neat and brilliant. Here is a simple explanation on how this works. 

The above regular expression will first try to match both Pattern not desired and Pattern desired. But only the Pattern desired will be shown in the capturing group since it is surrounded with the round brackets. Most regex engines will put this matched strings in a separate group. 

Here is a sample from Java which can demonstrate this trick.

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

public class RegExTrick {
	public static void main(String[] args){
		String str = "Get Hello From \"Hello\"";
		Pattern regex = Pattern.compile("\"Hello\"|(Hello)");
		Matcher matcher = regex.matcher(str);
		List capturingGroups = new ArrayList();

		while (matcher.find()) {
			if(null != {
		for(String matched : capturingGroups){

After reading the above explanation, the code should be self-explanatory.

This trick is really useful while working on situations where  some patterns are desired while some other patterns are not desired.

 If you want to get a thorough understanding of this trick and its applications, you can read details from RexEgg.



Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious



No comment for this article.


When finding new things

By sonic0002