正则表达式检查特殊字符或数字

时间:2022-09-01 21:48:34

I have such regular expression which checked for at least one special character in the string:

我有这样的正则表达式,它检查字符串中至少有一个特殊字符:

^(.*[^0-9a-zA-Z].*)$

But how could i change this one to check for at least one special character or at leas one number in the string?

但是我怎么能改变这个来检查至少一个特殊字符或字符串中的一个数字?

2 个解决方案

#1


2  

.*[^a-zA-Z]+.*

would match anything followed by a special character followed by anything.

将匹配任何后跟一个特殊字符后跟任何东西。

Notice that I just removed the 0-9 from the character class (characters included in the square brackets).

请注意,我刚从字符类中删除了0-9(方括号中包含的字符)。

Also, I removed the ^ and $ markers -- those match the beginning and end of string respectively. You don't need it because you're making it redundant with the .* (match zero or more of any character) anyway.

此外,我删除了^和$标记 - 分别匹配字符串的开头和结尾。你不需要它,因为你无论如何都要使。*(匹配零或多个任何字符)多余。

In fact, if you're just checking if the string contains a special character, then the following is good enough:

实际上,如果您只是检查字符串是否包含特殊字符,那么以下内容就足够了:

[^a-zA-Z]

#2


1  

you can use the Expresso, it is a smart tool for generate RegExps Expresso

你可以使用Expresso,它是一个生成RegExps Expresso的智能工具

#1


2  

.*[^a-zA-Z]+.*

would match anything followed by a special character followed by anything.

将匹配任何后跟一个特殊字符后跟任何东西。

Notice that I just removed the 0-9 from the character class (characters included in the square brackets).

请注意,我刚从字符类中删除了0-9(方括号中包含的字符)。

Also, I removed the ^ and $ markers -- those match the beginning and end of string respectively. You don't need it because you're making it redundant with the .* (match zero or more of any character) anyway.

此外,我删除了^和$标记 - 分别匹配字符串的开头和结尾。你不需要它,因为你无论如何都要使。*(匹配零或多个任何字符)多余。

In fact, if you're just checking if the string contains a special character, then the following is good enough:

实际上,如果您只是检查字符串是否包含特殊字符,那么以下内容就足够了:

[^a-zA-Z]

#2


1  

you can use the Expresso, it is a smart tool for generate RegExps Expresso

你可以使用Expresso,它是一个生成RegExps Expresso的智能工具