Regex that matches a newline (\n) in C#

前端 未结 6 1950
你的背包
你的背包 2020-11-30 07:08

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

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


        
相关标签:
6条回答
  • 2020-11-30 07:40

    Counter-intuitive as it is, you could use both Multiline and Singleline option.

    Regex.Match(input, @"(.+)^(.*)", RegexOptions.Multiline | RegexOptions.Singleline)
    

    First capturing group will contain first line (including \r and \n) and second group will have second line.

    Why:

    • Multiline:

      ^ and $ match the beginning and end of each line (instead of the beginning and end of the input string).

    • Singleline:

      The period (.) matches every character (instead of every character except \n)

      see docs

    0 讨论(0)
  • 2020-11-30 07:47

    Actually it works but with opposite option i.e.

     RegexOptions.Singleline
    
    0 讨论(0)
  • 2020-11-30 07:54

    You are probably going to have a \r before your \n. Try replacing the \s with (\r\n).

    0 讨论(0)
  • 2020-11-30 07:55

    If you're trying to match line endings then you may find

    Regex.Match("string", "regex", RegexOptions.Multiline)
    

    helps

    0 讨论(0)
  • 2020-11-30 07:58

    Think I may be a bit late to the party, but still hope this helps.

    I needed to get multiple tokens between two hash signs.

    Example i/p:

    ## token1 ##
    ## token2 ##
    ## token3_a
    token3_b
    token3_c ##

    This seemed to work in my case:

    var matches = Regex.Matches (mytext, "##(.*?)##", RegexOptions.Singleline);

    Of course, you may want to replace the double hash signs at both ends with your own chars.

    HTH.

    0 讨论(0)
  • 2020-11-30 08:04

    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: \n, \r, \r\n, so instead of looking only for \n, you should perhaps use something like: [\n\r]+, or more exactly: (\n|\r|\r\n).

    0 讨论(0)
提交回复
热议问题