Java equivalent of Perl s operator ///?

I have code that I convert from Perl to Java. He uses regular expressions quite actively, including the s/// operator. I have been using Perl for a long time and am still getting used to the Java way of doing something. In particular, Strings seem more difficult to work with. Does anyone know or have a Java function that fully implements s/// ? So that he can handle something like this, for example:

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

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

+6
java regex perl
source share
3 answers

Take a look at the String replaceAll (...) method . Please note: Java does not support the \U (uppercase) function.

+1
source share

Nothing so neat, 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 template documents for the regex Java syntax - it does not completely overlap with Perl.


To get uppercase, select 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.

+6
source share

Given an instance of the String class, you can use the .replaceAll () method as follows:

 String A = "Test"; A.replaceAll("(\bi'?\b)","\U$1"); 

Change - ok too slow. It is also obvious that \ U is not supported according to another answer.

Note. I'm not sure how the greedy character suffers, you can try exploring the Java implementation if you need it.

+2
source share

All Articles