regex in java

From WebHostingNeeds.com
Jump to: navigation, search

Hello and welcome to my regex tutorial. Today, I will inform you on how to use regex in order to help you as a programmer.

Regex is a very good way of scripting and can help you immensely on the long run. Many methods on iBot currently use regex, such as the famous 'UberScriptUtils' by Eric.

To start using regex you must know about the Pattern class. This class is imported from java.util.regex.Pattern. Therefore, you must have this in your imports:

import java.util.regex.Pattern;

You can read more about this class in the official Javadocs here: http://java.sun.com/javase/7/docs/api/

If you need the Java 6 API, you can find it here: http://java.sun.com/javase/6/docs/api/

The Pattern class has several methods such as the Pattern.compile(String regex); in which many people currently use.

It has helpful information and comments that will guide you through, however, I will be laying out what you need to know here on this thread.

Pattern.compile("."); //Any character, meaning if you enter 'N' it will match, or if you enter '$' or '3', it will all match
Pattern.compile("\d"); //Remember that this is not a slash but a backwards slash, this stands for any digit from 0-9, if you enter '1', it will match, however, '10' will not.
Pattern.compile("\D"); //This is for anything other than '0-9' or [^0-9]
Pattern.compile("\s"); //This is basically any space, including tabs and new lines.
Pattern.compile("\S"); //Like \D, this is anything other than a black space or a tab.
Pattern.compile("\w"); //This is any character from a-z, both uncapitzlied and capitalized. This also works for any digit 0-9.
Pattern.compile("\W"); //Anything not a character from a-z, A-Z, 0-9. [^\w]
Pattern.compile(".*"); //This is any character repeating as many times as you want, many scripters use this method, if you enter 'Hello World', it will work, if you enter '34hkeg3h' it will also work as well.
Pattern.compile("[abcdefg]o"); //This is any letter from the brackets,  a-g + o. Meaning that if I enter ao, or bo, or co, or do, it will work but if you enter zo, it will not work as 'z' is not in the bracket. Can also be expressed as [a-g]o
Pattern.compile("[a-zC-H]a"); //In this case, the first letter can be a-z lowercase, C-H, uppercase + a. Meaninig that Da would work, ha would work, ca would work, and Fa would work as well since D, h, c, and F are all parts of a-zC-H
Pattern.compile("[^u]"); //This means that any character or symbol/single digit will work except for 'u' because it has the ^ before it.

Now this is about all that's there, also when doing something such as..

String g = "\d\d";
Pattern.compile(g);

This will not work as the String type uses backslashes as well and they stand for things, such as how \n means a new line.

You must do this instead:

String g = "\\d\\d";
Pattern.compile(g); 

Complete iBot neXus Scripting Tutorial by Durenir, Updated by Chen (Monopoly)

ibot