Matching any character followed by not numbers

问题: I am not good at RegEx. Though it seems very simple to achieve but I am not able to find out the way to match any characters followed by not numbers. I am trying with negat...

问题:

I am not good at RegEx. Though it seems very simple to achieve but I am not able to find out the way to match any characters followed by not numbers. I am trying with negative lookahead. If I use any word it is working as expected but if I try to match any character with square bracket, it is failing.

var pattern = /sample(?!d)/;
console.log(pattern.test("sample324")); //false
var pattern = /[a-z]+(?!d)/;
console.log(pattern.test("sample324")); //true but expect false

Thanks in advance.


回答1:

Problem is that [a-z]+(?!d) will let it match any 1+ characters not followed by a digit, so it will match sampl in your input satisfying assertion of non-digit at next position.

You may use this regex with a negative lookahead:

/^(?!.+d)/

This will fail the match if a digit appears anywhere in input after 1+ of any character.

RegEx Demo

For better efficiency, you may use this regex as well:

/^(?!D+d)/

Which fails if there 1+ non-digits followed by a digit anywhere in input.


回答2:

I think this may work:

var pattern = /[^0-9]/.test('mystring9')
  • 发表于 2018-12-29 02:10
  • 阅读 ( 193 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除