yoki
yoki

Reputation: 1816

Replace all regex matches in a row, conditionally and from a starting point

A little cumbersome description, but here's an example. I would like to turn s,

s="something in the beginning #and something here at the end"

into t,

t="something in the beginning #and_something_here_at_the_end".

That is, use a regex to replace all spaces with _, but ONLY if I'm at a row that contains the # character, and only in the sentence after it.

My problems is that I can use regex to look for s/(.*)#(.*) (.*)/\1#\2_\3/, but then I can't do this for an arbitrary number of spaces... and on the other hand, I can't use simply s/ /_/g, because it'll replace all the spaces before the # sign and also in rows without this sign at all (that I would like to keep as they are).

This is a toy example, I would like to know how to do this with regex in the general case.

Thanks!

Upvotes: 0

Views: 70

Answers (1)

Sebastian Proske
Sebastian Proske

Reputation: 8413

You can use the \G anchor, that matches at the position of the last position and \K to keep out things matched before. This leads to

(?:^[^\#]*#|(?!^)\G)[^\s]*\K(\s)

and replace it with _

  • ^[^\#]*# starts with the anchor for the start of the string, then matches any non-# and a #
  • (?!^)\G matches the position of the last match. there is a lookahead to ensure we are not at the start of the string (first run \G is initialized at the start)
    • [^\s]*\K matches any non whitespaces and then forgets the match until here
  • (\s) matches a whitespace

Demo: https://regex101.com/r/oU4hN4/1

Upvotes: 1

Related Questions