5

I want that my string didn't contain *,; and $. I use this code

private static boolean IsMatch(String s, String pattern) {
         try {
             Pattern patt = Pattern.compile(pattern);
             Matcher matcher = patt.matcher(s);
             return matcher.matches();
         } catch (RuntimeException e) {
           return false;
         }  
}



String regex ="[^*;$]";
System.out.println(IsMatch(url,regex));

But this method return always false. Can any one tell me what's the problem

0

4 Answers 4

4

Try using [^*;$]* for your regex. It'll return true if your string doesn't contain any of *, ; and $. I'm assuming you want your regex to match strings that don't contain any of those characters since you're already using ^ inside [ and ].

Sign up to request clarification or add additional context in comments.

1 Comment

@foufi: this returns true for me with your method: System.out.println(IsMatch("http://example.com", "[^*;$]*"));
2

Try this regex [^\\*;\\$]*. * and $ are special characters in regex.

Edit: If you're using Pattern you should use this regex: String regex = "^[^\\*;\\$]*$", since you want to match the whole string.

As an alternative you could just use url.matches("[^\\*;\\$]*"); where you don't need the first ^ and last $, since that method tries to match the whole string anyways.

1 Comment

True, I took ^ as a character, not the negation. Fixed that.
0

You need to take out ^ and $, because they can occur anywhere in your string.

String regex = "[\*,;\$]";

Note the backslash escaping the $ symbol. Edit: and the * symbol.

Comments

0

You will need to escape some of the characters like this [\^*;\$]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.