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

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

问题描述

正则表达式的 Java API 指出s 将匹配空格.所以正则表达式 \s\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天全站免登陆