最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - RegExp that match everything except letters - Stack Overflow

programmeradmin4浏览0评论

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]*$/

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]*$/
Share Improve this question edited Apr 2, 2013 at 10:30 kmb asked Apr 2, 2013 at 8:04 kmbkmb 8715 gold badges17 silver badges34 bronze badges 2
  • 1 /[^a-zA-Z]+/.test('1qweqwe') yields true. – Ja͢ck Commented Apr 2, 2013 at 8:09
  • @Jack This solution didn't work for me. I found correct RegExp like this: /^[^a-zA-Z]*$/ – kmb Commented Apr 2, 2013 at 10:31
Add a ment  | 

2 Answers 2

Reset to default 8

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
}
发布评论

评论列表(0)

  1. 暂无评论