开发者

validate string with regex on android

开发者 https://www.devze.com 2023-02-25 00:58 出处:网络
I want that my string didn\'t contain *,; and $. I use this code private static boolean IsMatch(String s, String pattern) {

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 f开发者_StackOverflow社区alse. Can any one tell me what's the problem


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 ].


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消