简体   繁体   English

Java Regex:仅允许某些字符,但不允许某些字符以字符串开头?

[英]Java Regex: Allow only certain characters, but don't allow certain characters to begin the string?

I'm fiddling around with Java regex, and I'm trying to come up with a pattern that allows a certain set of characters anywhere else BUT it can't start with certain characters in the allowed set. 我在摆弄Java正则表达式,并试图提出一种模式,该模式允许在其他任何地方都可以使用某些字符集,但是它不能以允许的字符集开头。

For example, let's say the allowed characters are from A to Z, but the string can't start with X or Z. How do I do that? 例如,假设允许的字符是从A到Z,但是字符串不能以X或Z开头。我该怎么做? I've come up with ^[XZ][^AZ]+ , and while it works otherwise, it allows the string to start with other letters that are not in the set (eg with punctuation). 我想出了^[XZ][^AZ]+ ,虽然它可以正常工作,但是它允许字符串以不在集合中的其他字母开头(例如标点符号)。

You can use this regex: 您可以使用此正则表达式:

^[A-WY][A-Z]*$
  • ^[A-WY] ensures that the first character is AW or Y ^[A-WY]确保第一个字符为AWY
  • [AZ]*$ will match 0 or more of any uppercase English letter [AZ]*$将匹配0个或多个大写英文字母

In general to exclude certain characters you can also use negative look-ahead: 通常,要排除某些字符,还可以使用否定预读:

^(?![XZ])[A-Z]+$

(?![XZ]) is negative lookahead to disallow X or Z at start. (?![XZ])为负前瞻,禁止在开始时使用XZ

Java regexes support subtraction in character classes; Java正则表达式支持字符类中的减法。 see http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html , which shows these as examples: 请参阅http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html ,其中将这些显示为示例:

[a-z&&[^bc]]    a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]]   a through z, and not m through p: [a-lq-z](subtraction)

So you could say 所以你可以说

[A-Z&&[^XZ]]

to mean any upper-case ASCII letter except X or Z. It really isn't needed here, but if you're using large classes like Posix character classes, it could be more useful. 表示除X或Z以外的任何大写ASCII字母。这里确实不需要,但是如果您使用的是Posix字符类之类的大型类,它可能会更有用。

Warning: Not all languages support this construct in regexes. 警告:并非所有语言都在正则表达式中支持此构造。 I'm pretty sure C++ and Javascript don't, and I don't actually know of another language that does but I haven't checked. 我很确定C ++和Javascript不会,而且我实际上不知道有另一种语言可以,但是我还没有检查。

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

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