【问题标题】:regular expression: remove spaces from part of a line正则表达式:从行的一部分中删除空格
【发布时间】:2021-11-17 02:33:29
【问题描述】:

我想从表达式的一部分中删除空格。

Input some other stuff goes here, "alpha bravo charlie delta echo"
Desired output some other stuff goes here, "alphabravocharliedeltaecho"

, "alpha 在某些行上是一个常量,之后我希望删除所有空格。

我目前正在与

Find: ^(.*, "alpha) (((\w*) )*)(\w*")$
Replace with: $1|$2|$3|$4|$5|$6|$7|$8 (pipes and extra outputs to see what was happening)
Results some other stuff goes here, "alpha|bravo charlie delta |delta |delta|echo"|||
Expected results some other stuff goes here, "alpha|bravo|charlie|delta|echo"|||

我尝试了正则表达式的变体,但还没有更好的结果。显然,由于无法分别捕获 bravocharlie,我不明白如何捕获每场比赛。

(这似乎是一个常见问题。我知道这是否是重复的,但我一直无法找到它。)

更新:

我已经使用下面的模式来完成工作,但我仍然想更好地理解这一点,以便能够一次性完成。

(^.*, "alpha )(\w+) (.*)$ 重复直到“全部替换:在整个文件中替换了 0 次”
(^.*, "alpha) (.*)$

【问题讨论】:

  • (?:\G(?!^)|"alpha\b)\S*+\K\h+ 应该足够了。

标签: regex notepad++


【解决方案1】:
  • Ctrl+H
  • 查找内容:(?:"alpha|\G(?!^)\w+)\K\h+(?=.*?")
  • 替换为:LEAVE EMPTY
  • 检查 环绕
  • CHECK 正则表达式
  • 取消选中 . matches newline
  • 全部替换

说明:

(?:             # non capture group
    "alpha          # literally
  |               # OR
    \G(?!^)         # restart from last match position, not at the beginning of line
    \w+             # 1 or more word character
)               # end group
\K              # forget all we have seen until this position
\h+             # 1 or more horizontal spaces
(?=.*?")        # positive lookahead, make sure we have a double quote after

屏幕截图(之前):

截图(之后):

【讨论】:

  • 因为"alpha 可以在逗号之前存在,所以我不得不将表达式更改为(?:, "alpha|\G(?!^)\w+)\K\h+(?=.*?")。感谢您的精彩解释。
  • @dougp:不客气,很高兴它有帮助。
猜你喜欢
  • 2021-04-10
  • 2018-06-11
  • 2020-10-27
  • 2016-06-17
  • 2011-11-01
  • 2012-11-15
  • 2018-11-20
  • 1970-01-01
  • 2022-11-30
相关资源
最近更新 更多