1

Example:

    String s1 = JOptionPane.showInputDialog("enter the string");
    String s2 = "h2ow |are you";
   
    
    if (s2.replace all("\\d+","").replaceAll("|", "").contains(s1))
        JOptionPane.showMessageDialog(null, "true");
    
    else
        JOptionPane.showMessageDialog(null, "false");

If I enter input as "how" the output is true

but, when I enter "how are" the output is false.

Is there a method to replace '|'(vertical bar)?

Community
  • 1
  • 1
clem
  • 61
  • 2
  • 6

3 Answers3

7

You need to escape the pipe character (|). Unescaped, it is the regular expression "or" operator.

Try this:

s2.replaceAll("\\d|\\|", "").contains(s1)

This uses a literal pipe (regex=\|, escaped for Java="\\|") and an actual or-pipe (|). It says, replace any digit or literal pipe character with nothing.

Note, as stated by @alfasin, the function is named replaceAll, not replace_all.

Also, if this function is going to be used repeatedly in the same execution, then consider reusing the matcher object, instead of using the string version (which creates a Matcher object each time).


Please consider bookmarking the Stack Overflow Regular Expression FAQ for future reference.

Community
  • 1
  • 1
aliteralmind
  • 18,274
  • 16
  • 66
  • 102
2

Additional to guys answer you can also use:

if (s2.replaceAll("[\\d\\|]","").contains(s1))

This regex is better on performance that doing .replaceAll twice or using | on regex (regex OR)

Federico Piazza
  • 27,409
  • 11
  • 74
  • 107
1

| means or with regex so escape the | to match the actual character:

if (s2.replaceAll("\\d+","").replaceAll("\\|", "").contains(s1))
BitNinja
  • 1,418
  • 1
  • 19
  • 25