Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can't do this in Java regex. You'd have to manually post-process using <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#toUpperCase%28%29" rel="noreferrer"><code>String.toUpperCase()</code></a> and <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#toLowerCase()" rel="noreferrer"><code>toLowerCase()</code></a> instead.</p> <p>Here's an example of how you use regex to find and capitalize words of length at least 3 in a sentence </p> <pre><code> String text = "no way oh my god it cannot be"; Matcher m = Pattern.compile("\\b\\w{3,}\\b").matcher(text); StringBuilder sb = new StringBuilder(); int last = 0; while (m.find()) { sb.append(text.substring(last, m.start())); sb.append(m.group(0).toUpperCase()); last = m.end(); } sb.append(text.substring(last)); System.out.println(sb.toString()); // prints "no WAY oh my GOD it CANNOT be" </code></pre> <hr> <h3>Note on <code>appendReplacement</code> and <code>appendTail</code></h3> <p>Note that the above solution uses <code>substring</code> and manages a <code>tail</code> index, etc. In fact, you can go without these if you use <a href="http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#appendReplacement%28java.lang.StringBuffer,%20java.lang.String%29" rel="noreferrer"><code>Matcher.appendReplacement</code></a> and <code>appendTail</code>.</p> <pre><code> StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, m.group().toUpperCase()); } m.appendTail(sb); </code></pre> <p>Note how <code>sb</code> is now a <a href="http://java.sun.com/javase/6/docs/api/java/lang/StringBuffer.html" rel="noreferrer"><code>StringBuffer</code></a> instead of <a href="http://java.sun.com/javase/6/docs/api/java/lang/StringBuilder.html" rel="noreferrer"><code>StringBuilder</code></a>. Until <code>Matcher</code> provides <code>StringBuilder</code> overloads, you're stuck with the slower <code>StringBuffer</code> if you want to use these methods.</p> <p>It's up to you whether the trade-off in less efficiency for higher readability is worth it or not.</p> <h3>See also</h3> <ul> <li><a href="https://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer-in-java"><code>StringBuilder</code> and <code>StringBuffer</code> in Java</a></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload