Question

How do I negate the regex [a-zA-Z]+[0-9]*? i.e. from a string '12-mar-14, 21, 123_4, Value123, USER, 12/2/13' I need to match values anything other than Value123 and USER. Can someone please explain how?

I'm trying to replace the string '12-mar-14, 21, 123_4, Value123, USER, 12/2/13' to '%Value123%USER%' in Java. Anything that doesn't match [a-zA-Z]+[0-9]* should be replaced with %

A regex that would give following outputs for corresponding inputs.

Input: '12-mar-14, 21, 123_4, Value123, USER, 12/2/13'

Output: '%Value123%USER%'

Input: '12-mar-14, 21, 123_4'

Output: '%'

Input: 'New, 12-Mar-14, 123, dat_123, Data123'

Output: '%New%Data123%'

Was it helpful?

Solution

Use this method:

//********** MODIFIED *************//
public static void getSentence(String line) {
    String text[] = line.split(",");
    String res = "";

    for (int i = 0; i < text.length; i++) {
        String word = text[i].trim();
        if (word.matches("[a-zA-Z]+[0-9]*")){
            if (!"".equals(res)) 
                res = res + "%";
            res = res + word;
        }
    }
    if ("".equals(res)) 
        res = "%";
    else
        res = "%" + res + "%";
    System.out.println(res);
}

...

this.getSentence("New, 12-Mar-14, 123, dat_123, Data123");
this.getSentence("12-mar-14, 21, 123_4, Value123, USER, 12/2/13");

Output:

%New%Data123%
%Value123%USER%
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top