基于 Java 的正则表达式允许字母数字字符和 ', 和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6343047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java-based regular expression to allow alphanumeric chars and ', and
提问by Mr Albany Caxton
I'm new to regular expressions in Java and I need to validate if a string has alphanumeric chars, commas, apostrophes and full stops (periods) only. Anything else should equate to false.
我是 Java 正则表达式的新手,我需要验证字符串是否仅包含字母数字字符、逗号、撇号和句号(句点)。其他任何东西都应该等同于错误。
Can anyone give any pointers?
任何人都可以提供任何指示吗?
I have this at the moment which I believe does alphanumerics for each char in the string:
我现在有这个,我相信对字符串中的每个字符都有字母数字:
Pattern p = Pattern.compile("^[a-zA-Z0-9_\s]{1," + s.length() + "}");
Thanks
谢谢
Mr Albany Caxton
奥尔巴尼·卡克斯顿先生
回答by aioobe
I'm new to regular expressions in Java and I need to validate if a string has alphanumeric chars, commas, apostrophesand full stops(periods) only.
我是新来的Java正则表达式,我需要验证一个字符串有字母数字字符,逗号,撇号和句号只(期)。
I suggest you use the \p{Alnum}
class to match alpha-numeric characters:
我建议您使用\p{Alnum}
该类来匹配字母数字字符:
Pattern p = Pattern.compile("[\p{Alnum},.']*");
(I noticed that you included \s
in your current pattern. If you want to allow white-space too, just add \s
in the character class.)
(我注意到你包含\s
在你当前的模式中。如果你也想允许空格,只需添加\s
字符类。)
From documentation of Pattern
:
[...]
\p{Alnum}
An alphanumeric character:[\p{Alpha}\p{Digit}]
[...]
[...]
\p{Alnum}
一个字母数字字符:[\p{Alpha}\p{Digit}]
[...]
You don't need to include ^
and {1, ...}
. Just use methods like Matcher.matches
or String.matches
to match the full pattern.
您不需要包含^
和{1, ...}
。只需使用像Matcher.matches
或String.matches
这样的方法来匹配完整的模式。
Also, note that you don't need to escape .
within a character class ([
...]
).
另请注意,您不需要.
在字符类 ( [
... ]
) 中转义。
回答by Herring
Pattern p = Pattern.compile("^[a-zA-Z0-9_\s\.,]{1," + s.length() + "}$");
回答by Bohemian
Keep it simple:
把事情简单化:
String x = "some string";
boolean matches = x.matches("^[\w.,']*$");