简体   繁体   English

java如何使用正则表达式替换N个空格

[英]java how to replace N number of spaces using regular expression

I like to display a text (input text in textArea) nicely in web page. 我喜欢在网页中很好地显示文本(在textArea中输入文本)。 So need to 所以需要

    1. change linebreaker \n to <br/>
    2. keep indentation: 
             replace 2 spaces with one space and &nbsp; 
             replace 3 spaces with one space and 2 &nbsp; 
             replace 4 spaces with one space and 3 &nbsp; 
             replace N spaces with one space and N-1 &nbsp;

Is there a way to replace the spaces using regular expression in JAVA? 有没有办法在JAVA中使用正则表达式替换空格? Thanks. 谢谢。

Underscores represent spaces: 下划线表示空格:
Find: (?<=_)_ 查找: (?<=_)_
Replace: &nbsp; 替换: &nbsp;

If you have to stick with regex, positive lookbehind is what you're looking for. 如果你坚持使用正则表达式, 正回顾后是你在找什么。
Basically, this will match each space which follows another space. 基本上,这将匹配紧随另一个空间的每个空间。

This should help you: 这应该可以帮助您:

String oldString="";
String newString = oldString.replaceAll("\n", "<br />").replaceAll("(?<= ) ", "&nbsp;");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM