Java Regex - 使用String的replaceAll方法替换换行符 [英] Java Regex - Using String's replaceAll method to replace newlines

查看:354
本文介绍了Java Regex - 使用String的replaceAll方法替换换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,只想用字符串 - linebreak--替换其中的所有换行符。

I have a string and would like to simply replace all of the newlines in it with the string " --linebreak-- ".

只需编写就足够了:

string = string.replaceAll("\n", " --linebreak-- ");

我对它的正则表达式部分感到困惑。换行符需要两个斜杠吗?这还不错吗?

I'm confused with the regex part of it. Do I need two slashes for the newline? Is this good enough?

推荐答案

不要使用正则表达式!。您只需要一个纯文本匹配来替换\ n

Don't use regex!. You only need a plain-text match to replace "\n".

使用 replace() 将文字字符串替换为另一个字符串:

Use replace() to replace a literal string with another:

string = string.replace("\n", " --linebreak-- ");

请注意 replace()仍然替换所有次出现, replaceAll() - 区别在于 replaceAll() 使用正则表达式进行搜索。

Note that replace() still replaces all occurrences, as does replaceAll() - the difference is that replaceAll() uses regex to search.

这篇关于Java Regex - 使用String的replaceAll方法替换换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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