Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regular Expressions

Tags:

java

regex

I am trying to write something like this:

Pattern p = Pattern.compile("Mar\\w");
Matcher m = p.matcher("Mary");

String result = m.replaceAll("\\w");

The result would ideally be "y". Any ideas?

like image 704
Keith Ó Dúlaigh Avatar asked Jun 18 '26 10:06

Keith Ó Dúlaigh


1 Answers

Your question is not so clear, but I think you want to use a lookahead:

Pattern p = Pattern.compile("Mar(?=\\w)");
Matcher m = p.matcher("Mary");
String result = m.replaceAll("");

See it online: ideone

Or you could use a capturing group:

Pattern p = Pattern.compile("Mar(\\w)");
Matcher m = p.matcher("Mary");
String result = m.replaceAll("$1");

See it online: ideone

like image 77
Mark Byers Avatar answered Jun 19 '26 22:06

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!