Pages

Monday, November 12, 2012

The all mighty regex

We often use regular expressions when programming.
In many occasions they make our live easier and help us avoiding lots of lines of code. I was just navigating around, and by a chance I found a blog that shows probably the one of coolest regex.
Have a look at this regular expression:


                                                                    
Personally I never used this one before. The thing that I find cool about it is, its simplicity.
For those who are not familiar with regex terminology, this one matches a character that is within(inclusive )the characters SPACE and tilde in the ASCII table.



Hehe.. cool, isn't it? I am looking forward to use it somewhere.

I can't resist, let's just give it a quick try :)

1:  import java.util.regex.Matcher;  
2:  import java.util.regex.Pattern;  
3:  public class AllMightyRegex {  
4:       public static void main(String[] args) {  
5:            String someASCIICharacters = "!#$%&\'()*+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";  
6:            Pattern pattern = Pattern.compile("[ -~]");  
7:            Matcher matcher;   
8:            for (int variableIndex = 0; variableIndex < someASCIICharacters.length(); variableIndex++) {  
9:                 matcher = pattern.matcher(getCharAt(someASCIICharacters, variableIndex));  
10:                 if(matcher.matches()) {  
11:                      System.out.println("The character: " + getCharAt(someASCIICharacters, variableIndex) + " matches the pattern");  
12:                 }  
13:            }  
14:       }  
15:       private static String getCharAt(String someASCIICharacters,  
16:                 int variableIndex) {  
17:            return someASCIICharacters.charAt(variableIndex) + "";  
18:       }  
19:  }  


No comments:

Post a Comment

Share with your friends