user799698
user799698

Reputation: 39

extract values with java regex

I begin with regex and i want extract values from a 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

Upvotes: 0

Views: 1467

Answers (2)

João Silva
João Silva

Reputation: 91299

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
    }

Upvotes: 1

user177800
user177800

Reputation:

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

Upvotes: 0

Related Questions