使用正则表达式选择所有字符,直到特定字词为止

时间:2018-01-16 23:34:47

标签: regex sublimetext3

我的文件如下:

1. Question text
A) some words
B) some words
multiline text
multiline text
multiline text
(Answer A)
2. Question text
A) some words
B) some words
multiline text
multiline text
multiline text
(Answer B)
3. Question text
A) some words
B) some words
multiline text
multiline text
multiline text
(Answer A)

我正在尝试删除B)和问题行的每一行之间的所有多行文字。所以,它应该是这样的:

1. Question text
A) some words
B) some words
(Answer A)

2. Question text
A) some words
B) some words
(Answer B)

3. Question text
A) some words
B) some words
(Answer A)

我使用了以下正则表达式:B\).*\n[^w]+\(Answer,但它选择了第一行与B)之间的所有字符,直到最后一次出现 (Answer,而不是我想要匹配的内容。

1 个答案:

答案 0 :(得分:0)

  • 控制 + ħ
  • 查找:^B\).*\R\K[\s\S]*?(\([^)]+\))
  • 替换:$1\n
  • 全部替换

<强>解释

^B\)            : literally B), at beginning of line
.*\R            : 0 or more any character, followed by any kind of newline
\K              : forget all we have seen until this position
[\s\S]*?        : 0 or more any character (including linebreak), not greedy
(               : start group 1
  \(            : open parenthesis
    [^)]+       : 1 or more any character that is not a close parenthesis
  \)            : close parenthesis
)               : end group 1

<强>替换

$1      : content of group 1 (ie. the answer)
\n      : a linebreak, you could use \r\n if necessary.

给定示例的结果:

1. Question text
A) some words
B) some words
(Answer A)

2. Question text
A) some words
B) some words
(Answer B)

3. Question text
A) some words
B) some words
(Answer A)
相关问题