2

I am using String.replaceAll(String, String) to replace some regular expression. Something like that:

"test Test tEsT wOrd".replaceAll("(?i)(\\w+)", "$1")

I need to replace this capture with its upper variant, are there any way to do this or I need to use java.util.regex.Matcher?

michael nesterenko
  • 14,222
  • 25
  • 114
  • 182
  • So you just want to capture upper case letters? – progrenhard Aug 28 '13 at 19:15
  • 4
    Java doesn't have a callback-variant of `replaceAll`. [This is the Java way to do it](http://stackoverflow.com/a/377484/1633117). – Martin Ender Aug 28 '13 at 19:16
  • @progenhard, expression could be more complex, usually I do not need to make _all_ letter upper case, just some of them matched by a regular expression. – michael nesterenko Aug 28 '13 at 19:16
  • 1
    @m.buettner: I think **[this solution](http://stackoverflow.com/a/1282099/20938)** is better. This way you don't have to worry about `$` or ``\`` in the replacement string causing run-time exceptions or corrupting the output. – Alan Moore Aug 28 '13 at 20:53
  • @AlanMoore well you could just run the replacement string through `Matcher.quoteReplacement()`. What I was really referring to was the general `appendReplacement`/`appendTail` pattern. I like the class though. – Martin Ender Aug 28 '13 at 20:58
  • possible duplicate of [Java Regex Replace with Capturing Group](http://stackoverflow.com/questions/1277990/java-regex-replace-with-capturing-group) – Alan Moore Aug 28 '13 at 20:59
  • @m.buettner: that's true. In fact, I was wondering why I hadn't think of that, until I remembered `quoteReplacement()` didn't yet exist when that code was written. – Alan Moore Aug 28 '13 at 21:06
  • @AlanMoore oh okay, I didn't know that it was a recent addition. – Martin Ender Aug 28 '13 at 21:34

1 Answers1

-1

Check out this String method: toUpperCase

What I would suggest (not tested) is to do something like:

 "test Test tEsT wOrd".replaceAll("[magic regex]", "$1".toUpperCase())

@David Knipe is correct (comment). The only other thing I could think of is something along the lines of First char to upper case BUT in this context that could get really messy really fast. If you find another way, its probably better, but going to leave this here just in case there is no other alternative.

Community
  • 1
  • 1
sparks
  • 736
  • 1
  • 9
  • 29