Marco Boi
Marco Boi

Reputation: 49

java regex: negation of a match

Although I read a large number of posts on the topic (in particular using lookarounds), I haven't understood if this more general case can be solved using regular expressions.

setup:
1) an input regex is passed in
2) the input regex is embedded in a negative regex so that
3) anything that is not identified by the input regex is matched

Example:

given:

input regex: "[-//s]";

and

text: "self-service restaurant"

I want a negative regex wherein to embed my input regex so that I can match my text as:

"self", "service", "restaurant"

Importantly, the negative regex should also be able to match a simple string like:

"restaurant"

Note, what I want to do could be achieved changing the input regex from

"[-//s]"

to

"[^-//s]"

Yet, I'm after a more general approach where any regular expression can be passed into a negative regex.

Upvotes: 3

Views: 2664

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

You could achieve this through matching or splitting.

  1. Through matching.

    String s = "self-service restaurant";
    Matcher m = Pattern.compile("[^-\\s]+").matcher(s);
    while(m.find()) {
        System.out.println(m.group());
    }
    

You need to put the pattern inside a negated character class to match all the chars except the one present inside the negated class.

  1. Through splitting.

    String s = "self-service restaurant";
    String parts[] = s.split("[-\\s]+");
    System.out.println(Arrays.toString(parts));
    

This would split your input according to one or more space or hyphen chars. Later you could join them to get your desired output.

  1. Through replacing.

    String s = "self-service restaurant";
    System.out.println(s.replaceAll("[-\\s]+", "\\\n"));
    

Upvotes: 1

Related Questions