Phoenix
Phoenix

Reputation: 8933

Regular expression in negation

I want this regex to yield just the string acl. How do I do that ? I keep getting 2013- ,even though I have a negation operator .

void testPattern()
     {
        Pattern pattern =
        Pattern.compile("^.*-");

        Matcher matcher =
        pattern.matcher("2013-acl");

        boolean found = false;
        while (matcher.find())
        {
            println matcher.group();

        }
      }

Upvotes: 2

Views: 206

Answers (5)

syb0rg
syb0rg

Reputation: 8247

Solution without a regex:

Use a StringBuilder to delete everything before the -.

String string1 = "2013-acl";
StringBuilder b = new StringBuilder(string1);
b.delete(0, defaultBrowser.lastIndexOf('-') + 1);
string1 = b.toString();
System.out.println(string1);

That program should print out acl. No need for a regex.

Solution if you need a regex:

String string1 = "2013-acl";
Matcher matcher = Pattern.compile("(?<=-).*$").matcher(string1);
if (matcher.find()) System.out.println(matcher.group());

That program should print out acl.

Upvotes: 1

Hugo Dozois
Hugo Dozois

Reputation: 8420

^ is the beginning of string operator not a negation operator.

If you want to match only the end I suggest using :

"-(\w+)"

(Don't forget to escape back slash in Java.)

Then retrieve what is matched in the $1 variable.

You can do this using using the Matcher.group() function.

Pattern pattern =
Pattern.compile("-(\\w+)");

Matcher matcher =
pattern.matcher("2013-acl");

matcher.find();
println matcher.group(1);

Upvotes: 0

user2030471
user2030471

Reputation:

Your pattern "^.*-" matches the input only till the hyphen.

Change it to "^.*-(.*)$" and instead of matcher.group() use matcher.group(1).

So with this modified pattern and using the same input:

  1. ^ matches beginning of the input
  2. First .* matches 2013
  3. - matches a -
  4. Second .* matches acl
  5. $ matches the end of the input

Parentheses around second .* make a capturing group. The captured pattern becomes obtainable with matcher.group(1).

Upvotes: 2

John Smith
John Smith

Reputation: 275

Why not just do acl as the regex? or acl$ if you only want it to match acl if it is at the end of the string

Upvotes: 0

Daedalus
Daedalus

Reputation: 1667

You could use this to get everything after the -: (?<=-).*$

However, as it has been pointed out... simply splitting on the - would be easier.

Upvotes: 1

Related Questions