Java equivalent of Perl's s/// operator?
I have some code that I'开发者_Go百科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.
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.
Have a look at String's replaceAll(...) method. Note that Java does not support the \U
(upper-case) feature.
Given an instance of a String class you can use the .replaceAll() method like so:
String A = "Test";
A.replaceAll("(\bi'?\b)","\U$1");
Edit - ok too slow. Also apparently \U isn't supported according to another answer.
Note - I'm not sure how the greedy symbol translates, you might want to try looking into Java's implementation if you need that specifically.
精彩评论