Skip first nn characters, take the rest with RegEx

后端 未结 3 1940
说谎
说谎 2021-01-22 15:19

I saw a question that used \\K that exists in Notepad++/pcre/PHP (reset starting point of match). However, I cannot find this option or its equivalent in Mastering Regular Expr

相关标签:
3条回答
  • 2021-01-22 15:39

    Give (?<=.{15}).+ a try.

    Play around here: http://refiddle.com/2te3

    0 讨论(0)
  • 2021-01-22 15:58

    Technichally those character are not skipped, as they are consumed and considered part of the match. If you would like to skip the characters, then you need a look behind

    (?<=(.){15})
    
    0 讨论(0)
  • 2021-01-22 16:00

    In PCRE, Oniguruma, Boost, ICU regex flavors \K is a kind of a lookbehind construct:

    There is a special form of this construct, called \K (available since Perl 5.10.0), which causes the regex engine to "keep" everything it had matched prior to the \K and not include it in $&. This effectively provides variable-length look-behind. The use of \K inside of another look-around assertion is allowed, but the behaviour is currently not well defined.

    In .NET, \K is not necessary since it has variable-width (or infinite-width) lookbehind.

    (?<=subexpression) is a positive lookbehind assertion; that is, the character or characters before the current position must match subexpression.

    To match a digit after the first 15 any characters, use

    (?<=^.{15})\d
    

    See demo

    Do not forget that to make the dot match a newline, you need to use RegexOptions.Singleline.

    A note from rexegg.com:

    The only two programming-language flavors that support infinite-width lookbehind are .NET (C#, VB.NET, …) and Matthew Barnett's regex module for Python.

    And as a bonus: your current requirement does not mean you depend on the infinite width lookbehind. Just use a capturing group:

    var s = Regex.Replace("1234567890123456", @"^(.{15})\d", "$1*");
    

    The last 6 will get replaced with * and the beginning will get restored in the resulting string using the $1 backreference.

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