I am using Sublime Text, and I was wondering if there is a way to do this with Regex:
I have multiple files that have different lines and text.
In each of them I have a line that starts with "NAME : " and continues with the name of the person:
NAME : john doe smithI am looking to use Regex to replace the spaces found in the text john doe smith with a character _, basically after the text NAME : , so the new line will be:
NAME : john_doe_smithSo far I have tried doing this: Matching the line that contains "NAME" (couldn't get it working with the full one "NAME : ") with Find:
^.*\b(NAME)\b.*$But I don't know how to replace the spaces after the match.
Is there a way to accomplish this with Regex?
02 Answers
Depending on your regex flavour, you can do:
- Find:
(?:^NAME : |\G(?!^))\w+\K\h - Replace:
_
A demo and explanation can be found here on Regex101.
6It depends on where you're using the regex:
The following uses sed:
sed ':redo s/^\(\s*NAME\s*:\s*\S\+\)\s\+\([^_[:space:]]\)/\1_\2/ ;t redo' filesThe trick here is the t redo, which does a conditional branch back to the label redo, to rerun the replacement until it fails.
Note that the pattern includes some glue to make spaces around the : optional, ignore trailing white space and reduce multiple spaces to a single _.