Java Regex只用非破坏空间替换多个空白 [英] Java Regex that only replaces multiple whitepaces with Non-Breaking Spaces

查看:84
本文介绍了Java Regex只用非破坏空间替换多个空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种用非空格替换多个空格的Java正则表达式。两个或多个空格应该用相同数量的非空格替换,但单个空格不应该被替换。这需要适用于任何数量的空格。

所以如果我的字符串是这样开始的:

 用不同的例子测试这个输出

看起来像这样:

 测试此功能& nbsp;& nbsp; OUT& nbsp;& nbsp;& nbsp; WITH&  & nbsp;& nbsp;& nbsp;& nbsp;& nbsp;& nbsp;  CASES 


解决方案

您也可以一起跳过正则表达式。

  String testStr =用不同的CASES测试这个; 
String _replaced = testStr.replace(,& nbsp;& nbsp;);
字符串替换= _replaced.replace(& nbsp;,& nbsp;& nbsp;);

我没有测试过这个,但是第一个发现了两个空格的所有情况并用非 - 休息空间。第二个发现的情况下有奇数个空格,并用两个nbsps来纠正它。


I am looking for a Java regex way of replacing multiple spaces with non-breaking spaces. Two or more whitespaces should be replaced with the same number of non-breaking spaces, but single whitespaces should NOT be replaced. This needs to work for any number of whitespaces. And the first characters could be 1 or more whitespaces.

So if my String starts off like this:

TESTING THIS  OUT   WITH    DIFFERENT     CASES

I need the new String to look like this:

TESTING THIS  OUT   WITH    DIFFERENT     CASES

解决方案

You could also skip the regex all together.

String testStr = "TESTING THIS  OUT   WITH    DIFFERENT     CASES";
String _replaced = testStr.replace("  ", "  ");
String replaced = _replaced.replace("  ", "  ");

I haven't tested this but the first one finds all cases of two spaces and replaces them with non-breaking spaces. The second finds cases where there were an odd number of white-spaces and corrects it with two nbsps.

这篇关于Java Regex只用非破坏空间替换多个空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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