简体   繁体   English

匹配除字母以外的所有内容的正则表达式

[英]RegExp that match everything except letters

I'm trying to write RegExp that match everyting except letters.我正在尝试编写匹配除字母之外的所有内容的 RegExp。 So far, I've wrote something like this:到目前为止,我已经写了这样的东西:

/[^a-zA-Z]+/

However, during tests, I've found that it works nicely when I write for example: 'qwe' or 'qqqqqweqwe123123' or something similar, BUT when I start String from number for example: '1qweqwe', it doesn't match.但是,在测试期间,我发现它在我编写例如:'qwe' 或 'qqqqqweqwe123123' 或类似的东西时效果很好,但是当我从数字开始字符串时,例如:'1qweqwe',它不匹配。

What do I have to do yet to match everything except letters at any position of my input String?除了输入字符串的任何位置的字母之外,我还需要做什么来匹配所有内容?

Thanks in advance.提前致谢。

Edit: Correct RegExp I found is:编辑:我发现的正确 RegExp 是:

/^[^a-zA-Z]*$/

What do I have to do yet to match everything except letters at any position of my input String?除了输入字符串的任何位置的字母之外,我还需要做什么来匹配所有内容?

You need to use regular expression flags to achieve this您需要使用正则表达式标志来实现这一点

try this试试这个

'1qwe2qwe'.match(new RegExp(/[^a-zA-Z]+/g))

it should return ["1", "2"]它应该返回["1", "2"]

the g flag at end of the regexp tells regexp engine to keep traversing the string after it has found one match.正则表达式末尾的g标志告诉正则表达式引擎在找到匹配项后继续遍历字符串。 Without g flag it just abandons traversal upon finding first match.如果没有g标志,它只会在找到第一个匹配项时放弃遍历。 You can find the reference here你可以在这里找到参考

Your regular expression is not anchored, so it will yield true for partial matches.您的正则表达式未锚定,因此对于部分匹配,它会产生true If the whole string should not contain letters:如果整个字符串不应包含字母:

if (/^[^a-zA-Z]+$/.test(str)) {
    // all characters are not alphabetical
}

Or rather, if all characters must be numeric (or empty string):或者更确切地说,如果所有字符都必须是数字(或空字符串):

if (/^\d*$/.test(str)) {
    // all characters are digits
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM