Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The accepted answer:</p> <pre><code>String commonChars = s.replaceAll("[^"+t+"]",""); </code></pre> <p>has a bug!!!</p> <p>What if the string <code>t</code> has a regex meta-character? In that case the <code>replaceAll</code> fails.</p> <p><a href="http://www.ideone.com/dsvjm" rel="nofollow"><strong>See this program</strong></a> as an example where the string <code>t</code> has <code>]</code> in it and <code>]</code> is a regex meta-character which marks the end of the character class. Clearly the program does not produce the expected output.</p> <p>Why?</p> <p>Consider:</p> <pre><code>String s = "1479K"; String t = "459LP]"; </code></pre> <p>Now the regex will become(just substitute <code>t</code>):</p> <pre><code>String commonChars = s.replaceAll("[^459LP]]",""); </code></pre> <p>Which says replace any character other than <code>4</code>,<code>5</code>,<code>9</code>,<code>L</code>,<code>P</code> <strong>followed by a</strong> <code>]</code> with nothing. Which is clearly not what you want.</p> <p>To fix these you need to escape the <code>]</code> in <code>t</code>. You can do it manually as:</p> <pre><code>String t = "459LP\\]"; </code></pre> <p>and the <a href="http://www.ideone.com/l6ySq" rel="nofollow"><strong>regex works fine</strong></a>.</p> <p>This is a common problem when using regex, so the <code>java.util.regex.Pattern</code> class provides a static method named <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html#quote%28java.lang.String%29" rel="nofollow"><strong>quote</strong></a> which can be used to do exactly this: quote the regex-metacharacters so that they are treated literally. </p> <p>So before using <code>t</code> in <code>replaceAll</code> you quote it as:</p> <pre><code>t = Pattern.quote(t); </code></pre> <p><a href="http://www.ideone.com/vV0m8" rel="nofollow"><strong>Program using quote method</strong></a> works as expected.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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