如何在regex中为Java String使用开始和结束标记? [英] How to use beginning and endline markers in regex for Java String?

查看:154
本文介绍了如何在regex中为Java String使用开始和结束标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下内容没有更改Android中的文字?

Why doesn't the following change the text for me in Android?

String content = "test\n=test=\ntest";
content = content.replaceAll("^=(.+)=$", "<size:large>$1</size:large>")

它返回原始值而不做任何更改。我希望它用替换中间 = test = < size:large> test< / size:large>

It returns the original value with no changes. I would expect it to replace the middle =test= with <size:large>test</size:large>

我在这里缺少什么?

编辑:好的,我明白为什么 ^ $ 不起作用。关键是我需要在行的开头和结尾都匹配文本的东西,例如:一行只包含= some text =。由于以下原因,大多数答案都不充分:

Okay, I understand why ^ and $ don't work. The point is that I need something that matches text both at the beginning and end of a line, e.g. a line that contains only "=some text=". Most of the answers given aren't sufficient, for the following reasons:

=(。+)= 不与行结尾有任何关系,因此在其中匹配任何不是并排的 = 的行。

=(.+)= doesn't have anything to do with line endings, so matches any line with two = in it that are not side by side.

。* =(。+)=。* 匹配整行,但与上一行有相同的问题

.*=(.+)=.* matches the whole line, but has the same problem as the previous

\ n =(。+)= \ n 靠近,但不会连续匹配两行(例如 test\\\
= test = \ n = test = \\\ lt
)它也不会匹配第一行或最后一行的实例

\n=(.+)=\n gets closer, but won't match two lines in a row (e.g. test\n=test=\n=test=\ntest) It also won't match an instance on the first or last line

(?< = \ n)=(。+)=(?= \ n)几乎可以正常工作,但再次与实例不匹配在第一行或最后一行

(?<=\n)=(.+)=(?=\n) almost works, but again won't match an instance on the first or last line

(?<!。)=(。+)=(?!。)是唯一一个看起来实际上匹配以 = 开头和结尾的每一行,但是$ 1包含替换字符串和原始字符串。

(?<!.)=(.+)=(?!.) is the only one that seems will actually match every line that starts and ends with =, for example, but $1 contains both the replacement and the original string.

content = content.replaceAll((?< =( \\ n | ^))=(。+)=(?=(\ n | $)),< size:large> $ 2< / size:large>); 是唯一可以实际应该做的事情的答案。

content = content.replaceAll("(?<=(\n|^))=(.+)=(?=(\n|$))", "<size:large>$2</size:large>"); is the only answer that seems to actually do what it should.

推荐答案

如果打开多线模式,原始正则表达式可以正常工作使用(?m)

Your original regex works fine if you turn on multiline mode, using (?m):

content = content.replaceAll("(?m)^=(.+)=$", "<size:large>$1</size:large>");

现在 ^ $ 确实在行边界处匹配。

Now ^ and $ do indeed match at line boundaries.

这篇关于如何在regex中为Java String使用开始和结束标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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