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
  • 122,468
  • 25
  • 185
  • 269
app
  • 733
  • 5
  • 15
  • 27

2 Answers2

3

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

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Jonathan Rosenne
  • 2,159
  • 17
  • 27
  • 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
  • 15,851
  • 3
  • 22
  • 28