user2694734
user2694734

Reputation: 401

Use multiple regex to check blacklisted patterns are there in the string

I have a string with value. I want to check whether there are back listed pattern there in that string.

ex: String myString="a/b[c=\"1\"=\"1\"]/c\^]

I want to check following patterns are there

  1. "1"="1"
  2. ^

I am using following code which always gives false

         String text    = "\"1\"=\"1\" ^ for occurrences of the http:// pattern.";

        String patternString = "\"1\"=\"1\"|^";

        Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);

        Matcher matcher = pattern.matcher(text);

        boolean matches = matcher.matches();

        System.out.println("matches = " + matches)

How can I check it with one line of regex.

Upvotes: 4

Views: 758

Answers (2)

MChaker
MChaker

Reputation: 2649

To check if BOTH "1"="1" and ^ are in the input String

Using regex:

String text    = "\"1\"=\"1\"  ^ for occurrences of the http:// pattern.";
Pattern p = Pattern.compile("\"1\"=\"1\".*\\^|\\^.*\"1\"=\"1\"");
Matcher m = p.matcher(text);
if(m.find())
    System.out.println("Correct String");

Using contains method:

String text    = "\"1\"=\"1\"  ^ for occurrences of the http:// pattern.";
if (text.contains("\"1\"=\"1\"") && text.contains("^"))
        System.out.println("Correct String");

Upvotes: 1

anubhava
anubhava

Reputation: 785491

Couple of issues with your code:

String patternString = "\"1\"=\"1\"|^";

Here ^ must be escaped since ^ is a special meta character so make it:

String patternString = "\"1\"=\"1\"|\\^";

Then this call:

boolean matches = matcher.matches();

should be changed to:

boolean matches = matcher.find();

as matches attempts to match full input string.

Upvotes: 2

Related Questions