You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查找字符串中最后一个非数字间且非末尾的空格?

问题:定位字符串中符合要求的最后一个空格

需要定位字符串中最后一个符合要求的空格,规则如下:

  • 不能是字符串末尾的空格
  • 不能处于两个数字之间
  • 可以位于数字之前或之后

示例

jumnsch@domain.com m 5180-3807-3679-8221 612 3/1/2010
                    ^
hello this card number 4444 5555 6666 7777
                      ^
hello this bob
          ^

原有尝试代码

Pattern pattern = Pattern.compile("\\s(?![\\d\\s]*\\d$)");
Matcher matcher = pattern.matcher(input);
int lastIndex = -1;
while(matcher.find()){
    lastIndex = matcher.start();
}

解决方案

1. 正确的正则表达式

\\s(?!\\s*$)((?<!\\d)|(?!\\d))
  • \\s:匹配空格字符
  • (?!\\s*$):负向预查,确保空格后不是全空格直到字符串结尾(排除末尾空格)
  • ((?<!\\d)|(?!\\d)):零宽断言逻辑或,确保空格要么左侧不是数字,要么右侧不是数字(排除两个数字之间的空格)

2. 无需while循环的实现(Java 9+)

利用Matcher.results()获取所有匹配结果,通过流操作直接提取最后一个匹配的起始位置:

Pattern pattern = Pattern.compile("\\s(?!\\s*$)((?<!\\d)|(?!\\d))");
Matcher matcher = pattern.matcher(input);
int lastIndex = matcher.results()
                       .mapToInt(MatchResult::start)
                       .max()
                       .orElse(-1);

如果使用Java 8及以下版本,可通过列表收集匹配位置后取最后一项(本质仍为循环,但写法更简洁):

List<Integer> positions = new ArrayList<>();
while (matcher.find()) {
    positions.add(matcher.start());
}
int lastIndex = positions.isEmpty() ? -1 : positions.get(positions.size() - 1);

内容的提问来源于stack exchange,提问作者lemon chow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 20:33:23