Reputation: 8933
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
Reputation: 8247
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.
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
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
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:
^
matches beginning of the input.*
matches 2013
-
matches a -
.*
matches acl
$
matches the end of the inputParentheses around second .*
make a capturing group. The captured pattern becomes obtainable with matcher.group(1)
.
Upvotes: 2
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
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