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      808    0    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

  SAVE AS PDF   MARK AS READ   MARK AS IMPORTANT

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

  RELATED


  0 COMMENT


No comment for this article.


  WRITE ARTICLE

IKEA Bookbook

By sonic0002
IKEA 2015 Catalogue bookbook. Download a free copy or upload yourself to IKEA. Give you an advice, IKEA, be careful of the DOS attack. If you are in mainland China, please watch the video IKEA Bookbook. To be honest. A very creative design.It gets over 10 million visits in less than 15 days.