[英]Javascript regex for symbol but not space
I want to test a string for a symbol (eg $%^&*
) so I use the following regex that works well: 我想测试一个符号的字符串(例如$%^&*
),所以我使用以下运行良好的正则表达式:
/[\W+]/.test(string)
However, a space is also matched with this regex. 但是,该正则表达式也匹配一个空格。 What I really want is to test for a symbol but not a space. 我真正想要的是测试符号而不是空格。 I'm trying the following code, but a space is still matched: 我正在尝试以下代码,但仍匹配一个空格:
/[\W\S+]/.test(string)
Is there a better way to do this? 有一个更好的方法吗?
Since the whitespaces are included in \\W
, you need to use a negated character class: 由于\\W
中包含空格,因此您需要使用否定的字符类:
[^\w\s]
However, you must clearly define what you call a "symbol" since this character class include for example accentued letters and all out of the ascii range. 但是,您必须明确定义您所谓的“符号”,因为此字符类包括例如重音字母和所有不在ASCII范围内的字符。
\\W
is the equivalent of [^A-Za-z0-9_]
, meaning "any character except these." \\W
等效于[^A-Za-z0-9_]
,表示“除这些字符外的任何字符”。 So you can use [^A-Za-z0-9_ ]
(note the space at the end) to exclude spaces. 因此,您可以使用[^A-Za-z0-9_ ]
(注意末尾的空格)来排除空格。
You may use the inverse shorthand character class for \\W
(which is \\w
) and use a negation in the character class: 您可以将反简写字符类用于\\W
(即\\w
),并在字符类中使用负号:
/[^\w\s]+/.test(string)
Your regex [\\W\\S+]
is also matching literal +
as it is part of a character class. 您的正则表达式[\\W\\S+]
也匹配文字+
因为它是字符类的一部分。 I think you need to place it outside the class to match 1 or more characters. 我认为您需要将其放置在课程之外,以匹配1个或更多字符。
This regex may help you: [^\\s\\w]
此正则表达式可以帮助您: [^\\s\\w]
https://regex101.com/r/jO4uU6/3 https://regex101.com/r/jO4uU6/3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.