Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]*$/
like image 258
kmb Avatar asked Apr 02 '13 08:04

kmb


2 Answers

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

like image 91
Ejaz Avatar answered Oct 15 '22 02:10

Ejaz


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
}
like image 21
Ja͢ck Avatar answered Oct 15 '22 03:10

Ja͢ck