The Greatest Regex Trick Ever (Simplified)

  sonic0002        2015-10-01 21:59:05       5,117        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 != matcher.group(1)) {
				capturingGroups.add(matcher.group(1));
			}
		}
		
		for(String matched : capturingGroups){
			System.out.println(matched);
		}
	}
}

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.

JAVA  PROGRAMMING  REGULAR EXPRESSION 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Teamwork! Teamwork!