java 正则 连续数字_Java - 正则表达式匹配字符串中的连续数字或字符

该博客演示了一个Java方法,用于检查输入字符串中是否存在连续数字或字符,且数量不超过指定的最大值。通过遍历字符串并比较字符之间的差异来实现功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是一个快速,肮脏,未优化(可能是越野车),但你想要实现什么样的独立示例。

public static void main(String[] args) {

// should not allow

System.out.println(hasValidSequence("abcd", 3));

// should not allow

System.out.println(hasValidSequence("1234", 3));

// should allow

System.out.println(hasValidSequence("abcd", 4));

// should allow

System.out.println(hasValidSequence("1234", 4));

}

public static boolean hasValidSequence(String input, int maxAllowed) {

// boilerplate validation of empties/nulls

if (input == null || input.isEmpty()) {

// TODO handle better?

return false;

}

// counter for blowing things up if reached

int counter = 0;

// char takes int values - initializing as bogus 0

char c = (char)0;

// iterating input String characters one by one

for (int i = 0; i < input.length(); i++) {

// previous char is next char as int, - 1 --> they're successive

// you can fool around and replace with input.charAt(i) <= i

// for indirect sequences or same characters

// TODO check it's an alpha numeric!

if (c == input.charAt(i) - 1) {

// incrementing counter

counter++;

}

// assigning current char

c = input.charAt(i);

// counter reached? we blow things up!

if (counter == maxAllowed) {

return false;

}

}

// no counter reached, return true

return true;

}

输出

false

false

true

true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值