简体   繁体   English

正则表达式用于增加/减少数字模式

[英]Regex for increasing/decreasing number pattern

How can I test for an increasing or decreasing number pattern in a string? 如何测试字符串中的递增或递减数字模式? Assuming the string is just a number. 假设字符串只是一个数字。

Ex: 例如:

var regexp = new RegExp(...) // something here
regexp.test("123456789") //true
regexp.test("121231234") //false
regexp.test("987654321") //true
regexp.test("5678901234") //true

The test would be for a cycle of digits really. 测试实际上是一个数字周期。 How could this be achieved? 如何做到这一点?

This mess of a regex is the best I can produce. 这种混乱的正则表达式是我能生产的最好的。 It finds groups of ascending or descending numbers. 它查找升序或降序的组。 You'd need to throw a starting and ending check on either end but, I didn't know what kind you want. 您需要在任一端都进行开始和结束检查,但是,我不知道您想要哪种。 For example you may want to have start line(^) and end line($) wrapped around this regex. 例如,您可能希望在此正则表达式周围包含开始行(^)和结束行($)。 It uses lookaheads which you may want to lookup if you are unfamiliar http://www.regular-expressions.info/lookaround.html . 如果您不熟悉http://www.regular-expressions.info/lookaround.html,它会使用先行查询。

(((?=01|12|23|34|45|56|67|78|89|90)\d)+|((?=
09|98|87|76|65|4|43|32|21|10)\d)+)\d

I'm not sure that you can achieve that with regex, but definitely can do that with reduce . 我不确定您可以使用regex实现此功能,但可以肯定地使用reduce

 const test = ["123456789", "121231234", "987654321", "5678901234"]; const results = test .map((item) => item.split('')) .map((item) => { let lastDigit = item[0]; return item.slice(1).reduce((flag, digit) => { const ret = flag && digit > lastDigit; lastDigit = digit; return ret }, true) }); console.log(results); 

If you actually need to use regexp to do this, then this is simplest solution that comes to my mind: 如果您实际上需要使用regexp来执行此操作,那么这是我想到的最简单的解决方案:

/(^0*1*2*3*4*5*6*7*8*9*$)|(^9*8*7*6*5*4*3*2*1*0*$)/

* means "any number of". *表示“任意数量”。

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

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