空白匹配正则表达式 - Java [英] Whitespace Matching Regex - Java

查看:128
本文介绍了空白匹配正则表达式 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正则表达式的Java API声明 \s 将匹配空格。所以正则表达式 \\\\\ 应匹配两个空格。

The Java API for regular expressions states that \s will match whitespace. So the regex \\s\\s should match two spaces.

Pattern whitespace = Pattern.compile("\\s\\s");
matcher = whitespace.matcher(modLine);
while (matcher.find()) matcher.replaceAll(" ");

这样做的目的是用一个空格替换两个连续空格的所有实例。然而,这实际上并不起作用。

The aim of this is to replace all instances of two consecutive whitespace with a single space. However this does not actually work.

我对正则表达式或术语空格有严重的误解吗?

Am I having a grave misunderstanding of regexes or the term "whitespace"?

推荐答案

是的,你需要获取matcher.replaceAll()的结果:

Yeah, you need to grab the result of matcher.replaceAll():

String result = matcher.replaceAll(" ");
System.out.println(result);

这篇关于空白匹配正则表达式 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆