Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equivalent of Perl's s/// operator?

Tags:

java

regex

perl

I have some code that I'm converting from Perl to Java. It makes pretty heavy use of regular expressions, including the s/// operator. I've been using Perl for a long time and am still getting used to the Java way of doing things. In particular, Strings seem more difficult to work with. Does anyone know of or have a Java function that fully implements s///? So that it could handle something like this, for example:

$newString =~ s/(\bi'?\b)/\U$1/g;

(Maybe not a great example, but you get the idea.) Thanks.

like image 461
reid Avatar asked Feb 12 '10 20:02

reid


2 Answers

Nothing so tidy, but in Java you would use String.replaceAll() or use Pattern to do something like:

Pattern p = Pattern.compile("(\bi'?\b)");

Matcher m = p.matcher(stringToReplace);
m.replaceAll("$1");

Check the Pattern docs for Java's regex syntax--it doesn't overlap completely with Perl.


To get uppercasing, check out Matcher.appendReplacement:

StringBuffer sb = new StringBuffer();
while (m.find()) {
    String uppercaseGroup = m.group(1).toUpperCase();
    m.appendReplacement(sb, uppercaseGroup);
}
m.appendTail();

Not as close to Perl as the jakarta-oro library referenced above, but definitely some help built into the library.

like image 80
Michael Brewer-Davis Avatar answered Sep 22 '22 11:09

Michael Brewer-Davis


Have a look at String's replaceAll(...) method. Note that Java does not support the \U (upper-case) feature.

like image 35
Bart Kiers Avatar answered Sep 18 '22 11:09

Bart Kiers