基于Java的正则表达式,允许使用字母数字字符和',和 [英] Java-based regular expression to allow alphanumeric chars and ', and

查看:980
本文介绍了基于Java的正则表达式,允许使用字母数字字符和',和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java中正则表达式的新手,我需要验证字符串是否只包含字母数字字符,逗号,撇号和句号(句点)。其他任何东西都应该等于假。

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.

任何人都可以提供任何指示吗?

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() + "}");

谢谢

Albany Caxton先生

Mr Albany Caxton

推荐答案


我是Java中正则表达式的新手,我需要验证字符串是否正确只有字母数字字符逗号撇号句号(句点)。

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.

我建议您使用 \p {Alnum} 类来匹配字母数字字符:

I suggest you use the \p{Alnum} class to match alpha-numeric characters:

Pattern p = Pattern.compile("[\\p{Alnum},.']*");

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

(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.)

来自 <$ c的文档$ c>模式


[...]

[...]

\p {Alnum} 一个字母数字字符: [\p {Alpha} \p {Digit} ]

\p{Alnum} An alphanumeric character:[\p{Alpha}\p{Digit}]

[...]






您不需要包含 ^ {1,...} 。只需使用 Matcher.matches String.matches 等方法来匹配完整模式。


You don't need to include ^ and {1, ...}. Just use methods like Matcher.matches or String.matches to match the full pattern.

另外,请注意,您不需要在字符类中转义 [ ... ] )。

Also, note that you don't need to escape . within a character class ([...]).

这篇关于基于Java的正则表达式,允许使用字母数字字符和',和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆