Continuing talking about java tips and tricks .. here's one of my favorite tricks :) ..
Regular Expressions :
- So what are Regular Expressions ? Do you know The Command Line in Windows or Terminal in linux .. There're always some sort of commands that are built into it in order to do specific tasks. E.x. in Linux : "ls" lists all the files in the current directory ,"pwd" Prints the current directory,"cd" Change the directory to the folder specified after calling it .. and so on ..
- Regular Expressions are just the same .. but in the split method contained in the String Class !! .. Let's start taking examples so you get to know what I'm talking about ..
String stn = "My Name is Ahmed";
String[] array = stn.split(" ");
- What this does is that it breaks the sentence on the spaces .. This is actually very common and nothing is special here.
- What if we wanted to break the sentence using more than one character ? ..
String stn = "My,Name.is!Ahmed";
String[] array = stn.split("[,.!]");
- What this will do is simply break the sentence on the characters BETWEEN the [] .. the [] is just used to tell the method what characters that will be used .. try use it without the [] ,it won't work ..
- Lets take another problem what if multiple of those characters found consecutive in the sentence ? .. using the previous way it will result in an empty Strings in the String array , what we want to do is tell the method to deal with those consecutive characters as a whole chunk and break the sentence around it.
String stn = "My,Name. !?!is!Ahmed";
String[] array = stn.split("[ ,.!?]+");
- We just add + after the [] to till the method that those characters can come in a consecutive way ..
- Now another problem , what if we wanted to break the sentence using a wide range of characters ? .. E.x. we want to break on the Numbers from zero to nine ?
String stn = "My1Name6is9Ahmed";
String[] array = stn.split("[1234567890]");
OR .. String[] array = stn.split("[0-9]");
- The - means from to .. from 0 -> 9 ..
- Now I'll introduce you to a new Expression which is "^" .. what this does is invert the set of characters given .. What I mean is what if I wanted to only keep the Numbers and delete everything else ? ..
String stn = "My1Name6is9Ahmed";
String[] array = stn.split("[^0-9]");
- There're still a wide range of Expressions .. I will show some of them to you and let you figure out what they do :) ..
String stn = "My1Name6is9Ahmed";
String[] array = stn.split("(Name|Ahmed)");
String stn = "My1Name111is11111Ahmed";
String[] array = stn.split("1{2,4}");
###################################################################
Here's an interesting article about it on TC ..
if you have found an interesting Expression don't hesitate to share it here :) :) ..