基于 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:29:26  来源:igfitidea点击:

Java-based regular expression to allow alphanumeric chars and ', and

javaregex

提问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 \sin your current pattern. If you want to allow white-space too, just add \sin the character class.)

(我注意到你包含\s在你当前的模式中。如果你也想允许空格,只需添加\s字符类。)

From documentation of Pattern:

文档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.matchesor String.matchesto match the full pattern.

您不需要包含^{1, ...}。只需使用像Matcher.matchesString.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.,']*$");