简体   繁体   中英

Java string validation using regex

I need to validate an input string using regex.

The requirement is:

The input

  1. must not start with % , _

  2. must not contain & , # , > , <

  3. may be empty

I have used [^%_#&<>][^#&<>]*|^$ successfully.

Is there any better way to address the problem?

Your regex is wrong, you should also place ^ and $ constraints on the first variant:

^[^%_#&<>][^#&<>]*|$

This because the first case can be applied on a substring .

The regex you defined simply states: an empty string, or a string with at least one character that is not % , _ , # ,...

It think the proposed regex is good enough. Some (probably not java) regex libraries offer additional functionality to state that the string should not contain a certain character. But since the regex is not that complex, it won't help that much.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM