首页 > 解决方案 > How tho get the whole section with regex (until a line doesn't start with whitespace )

问题描述

I have the next string:

Numbers: Zero
     One
   Two
    Three
  ***
  (n lines that start with one or more whitespace chars)
  ***
Name\Fruits\etc: John
  Jane

I want to get (with regex) the string that starts with "Numbers:" until the next line that starts with non-whitespace character (without this line...).

I my example, the next line after "Numbers:" that starts with non-whitespace character is: "Name\Fruits\etc: John", so I want to get:

  Zero
     One
   Two
    Three
  ***
  (n lines that start with one or more whitespace chars)
  ***

标签: c#regex

解决方案


你可以用这个

^(?:Numbers:)([\w\W]+?)(?=^\S)
  • ^- 锚定到字符串的开头。
  • (?:Numbers:) - 非捕获组,匹配Numbers:.
  • ([\w\W]+?)- 匹配任何东西。(懒惰模式)。
  • (?=^\S)- 必须后跟非空格字符的换行符。

演示


推荐阅读