开发者

Multiline regular expression in C# [duplicate]

This question already has answers here: How do I match any character across multiple lines in a regular expression? (26 answers) Closed 3 years ago.

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

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

Input:

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

Output:

[tag name="abc"]this
is
a
test
[/tag开发者_如何学JAVA]

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.


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

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...?

Example

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]");


Here's a regex to match. It requires the RegexOptions.Singleline option, which makes the . match newlines.

<(\w+) name="([^"]*)">(.*?)</\1>

After this regex, the first group contains the tag, the second the tag name, and the third the content between the tags. So replacement string could look like this:

[$1 name="$2"]$3[/$1]

In C#, this looks like:

newString = Regex.Replace(oldString, 
    @"<(\w+) name=""([^""]*)"">(.*?)</\1>", 
    "[$1 name=\"$2\"]$3[/$1]", 
    RegexOptions.Singleline);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜