简体   繁体   English

使用正则表达式进行Java字符串验证

[英]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. 一些(可能不是Java)正则表达式库提供了附加功能,以声明字符串不应包含某个字符。 But since the regex is not that complex, it won't help that much. 但是由于正则表达式并不是那么复杂,所以它不会有太大帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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