在C#中多行定期EX pression [英] Multiline regular expression in C#

查看:170
本文介绍了在C#中多行定期EX pression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何匹配和多行模式下使用常规的前pressions替换文本?

How do I match and replace text using regular expressions in multiline mode?

我知道<一个href=\"https://msdn.microsoft.com/en-us/library/yd1hzczs%28v=vs.110%29.aspx\">RegexOptions.Multiline选项​​,但什么是指定匹配在C#中的所有新行字符的最佳方式?

I know the RegexOptions.Multiline option, but what is the best way to specify match all with the new line characters in C#?

输入:

<tag name="abc">this
is
a
text</tag>

输出:

[tag name="abc"]this
is
a
test
[/tag]


啊哈,我发现的实际问题。 '和;'和;在正则表达式是匹配的单行文本,而同样需要在正则表达式进行转义在有新的生产线也个案工作。


Aahh, I found the actual problem. '&' and ';' in Regex are matching text in a single line, while the same need to be escaped in the Regex to work in cases where there are new lines also.

推荐答案

如果你的意思是有具有的是为前pression匹配一个换行符,那么 \\ n 会为你做的。

If you mean there has to be a newline character for the expression to match, then \n will do that for you.

否则,我想你可能误会了多行/单行标志。如果你希望你的前pression跨越几行匹配,你真的想使用 RegexOptions.Singleline 。它的意思是,将整个输入字符串为单行,从而忽略换行。这是你以后...?

Otherwise, I think you might have misunderstood the Multiline/Singleline flags. If you want your expression to match across several lines, you actually want to use RegexOptions.Singleline. What it means is that it treats the entire input string as a single line, thus ignoring newlines. Is this what you're after...?

示例

Regex rx = new Regex("<tag name=\"(.*?)\">(.*?)</tag>", RegexOptions.Singleline);
String output = rx.Replace("Text <tag name=\"abc\">test\nwith\nnewline</tag> more text...", "[tag name=\"$1\"]$2[/tag]");

这篇关于在C#中多行定期EX pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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