简体   繁体   中英

RegExp that match everything except letters

I'm trying to write RegExp that match everyting except letters. 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.

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:

/^[^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"]

the g flag at end of the regexp tells regexp engine to keep traversing the string after it has found one match. Without g flag it just abandons traversal upon finding first match. You can find the reference here

Your regular expression is not anchored, so it will yield true for partial matches. 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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