Home > Net >  regular expression: remove spaces from part of a line
regular expression: remove spaces from part of a line

Time:09-24

I want to remove spaces from part of an expression.

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

, "alpha is a constant on some lines after which I want all spaces removed.

I am currently working with

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"|||

I tried variations of the regular expression, but haven't had better results yet. Clearly, being unable to capture bravo and charlie separately, I'm not understanding how to capture every match.

(This seems like it would be a common question. I understand if this is a duplicate, but I have been unable to find it.)

Update:

I have used the pattern below to get the job done, but I still want to understand this better to be able to do it in a single pass.

(^.*, "alpha )(\w ) (.*)$ repeated until "Replace All: 0 occurrences were replaced in the entire file"
(^.*, "alpha) (.*)$

CodePudding user response:

  • Ctrl H
  • Find what: (?:"alpha|\G(?!^)\w )\K\h (?=.*?")
  • Replace with: LEAVE EMPTY
  • CHECK Wrap around
  • CHECK Regular expression
  • UNCHECK . matches newline
  • Replace all

Explanation:

(?:             # 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

Screenshot (before):

enter image description here

Screenshot (after):

enter image description here

  • Related