[英]Regex to remove special characters from a string
I'm trying to write a regex that only allows letters, numbers, single white spaces, '-'
literal, and '/'
literal.我正在尝试编写一个只允许字母、数字、单个空格、 '-'
字面量和'/'
字面量的正则表达式。 How do I limit my expression to only these?我如何将我的表达限制在这些?
If I enter "This should be invalid because it ends with!!! these"
, it is still returned as a valid string, even though there's an exclamation at the end.如果我输入"This should be invalid because it ends with!!! these"
,它仍然作为有效字符串返回,即使末尾有一个感叹号。
The one I have is not entirely correct:我所拥有的并不完全正确:
[A-Z]|[a-z]|[0-9]|/|\s|-
The problem here is that, by default, regular expressions do not have to match the entire string.这里的问题是,默认情况下,正则表达式不必匹配整个字符串。 One character is sufficient to constitute a match (and sometimes even none)!一个字符就足以构成匹配(有时甚至没有)! You need to surround your regex like ^(?: ... )+$
to make it work as you want:您需要像^(?: ... )+$
一样包围您的正则表达式,使其按您的意愿工作:
console.log([ 'This should be invalid because it ends with!!! these', //=> false 'This is valid' //=> true ].map(/ /.test, /^(?:[AZ]|[az]|[0-9]|\\/|\\s|-)+$/ ))
However, a more compact way to write the same expression would be ^[A-Za-z\\d\\s\\/-]+$
.但是,编写相同表达式的更紧凑的方法是^[A-Za-z\\d\\s\\/-]+$
。
console.log([ 'This should be invalid because it ends with!!! these', //=> false 'This is valid' //=> true ].map(/ /.test, /^[A-Za-z\\d\\s\\/-]+$/ ))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.