extract values with java regex
I begin with regex and i want extract values from a开发者_JAVA百科 String like this
String test="[ABC]Name:User:Date: Adresse ";
I want extract Name, User , Date and Adresse I can do the trick with substring and split
String test = "String test="[ABC]Name:User:Date: Adresse ";
String test2= test.substring(5,test.length());
System.out.println(test2);
String[] chaine = test2.split(":");
for(String s :chaine)
{
System.out.println("Valeur " + s);
}
but i want try with regex , i did
pattern = Pattern.compile("^[(ABC)|:].");
but it doesn ' t work
Can you help me please ?
Thanks a lot
String#split
is really the best way to accomplish what you are trying to do. Having said that, with regex, the following will give you the same output:
Pattern p = Pattern.compile("^(?:\\[ABC\\])([^:]+):([^:]+):([^:]+):([^:]+)$");
Matcher m = p.matcher(test);
while (m.find()) {
System.out.println("Valeur " + m.group(1)); // Name
System.out.println("Valeur " + m.group(2)); // User
System.out.println("Valeur " + m.group(3)); // Date
System.out.println("Valeur " + m.group(4)); // Address
}
You have to escape the [
and ]
here is a working example.
^\[(.*)\](.*):(.*):(.*):(.*)$
Note that your code is probably more easily maintained than regular expressions in cases where the regular expression becomes complex.
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. - Jamie Zawinski
精彩评论