Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

.net - Regex that matches a newline ( ) in C#

OK, this one is driving me nuts.... I have a string that is formed thus:

var newContent = string.Format("({0})
{1}", stripped_content, reply)

newContent will display like:
(old text)
new text

I need a regular expression that strips away the text between parentheses with the parenthesis included AND the newline character.

The best I can come up with is:

const string  regex = @"^((.*)s)?(?<capture>.*)";
var match= Regex.Match(original_content, regex);
var stripped_content = match.Groups["capture"].Value;

This works, but I want specifically to match the newline ( ), not any whitespace (s) Replacing s with \n or \ does NOT work.

Please help me hold on to my sanity!

EDIT: an example:

public string Reply(string old,string neww)
        {
            const string  regex = @"^((.*)s)?(?<capture>.*)";
            var match= Regex.Match(old, regex);
            var stripped_content = match.Groups["capture"].Value;
            var result= string.Format("({0})
{1}", stripped_content, neww);
            return result;
        }

Reply("(messageOne)
messageTwo","messageThree") returns :
(messageTwo)
messageThree
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you specify RegexOptions.Multiline then you can use ^ and $ to match the start and end of a line, respectively.

If you don't wish to use this option, remember that a new line may be any one of the following: , , , so instead of looking only for , you should perhaps use something like: [ ]+, or more exactly: ( | | ).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...