0

Regular Expressions in java

String s1="Anil-anilorg|anotherorg";
String s2="Anil-anilorg|";

I want to find weather s2 is present or sub-string of s1 by using regular expressions, but while I am doing that it is considering this symbol "|" as logical OR I am using hbaseStringRegexComparator to compare

Pshemo
  • 118,400
  • 24
  • 176
  • 257
app
  • 693
  • 2
  • 12
  • 26

2 Answers2

3

You need to escape the | as \|, and within a String it becomes "\\|".

Pshemo
  • 118,400
  • 24
  • 176
  • 257
Jonathan Rosenne
  • 2,083
  • 18
  • 25
  • can you please explain me why do it need two back \\? – app Dec 07 '17 at 15:47
  • Within a string literal the backslash is the escape symbol. A single backslash will escape the logical or symbol and the regex will consequently contain just it. A double backslash will escape the backslash so the regex with contain \| as required. – Jonathan Rosenne Dec 07 '17 at 15:50
  • Thank you it worked – app Dec 07 '17 at 15:53
1

You can use String.contains method. No regex needed:

    String s1="Anil-anilorg|anotherorg"; 
    String s2="Anil-anilorg|"; 
    System.out.println(s1.contains(s2));
Eritrean
  • 13,003
  • 2
  • 20
  • 25