开发者

Regex to replace all ocurrences of a given character, ONLY after a given match

开发者 https://www.devze.com 2023-01-11 07:51 出处:网络
For the sake of simplicity, let\'s say that we have input strings with this format: *text1*|*text2* 开发者_开发技巧

For the sake of simplicity, let's say that we have input strings with this format:

*text1*|*text2*
开发者_开发技巧

So, I want to leave text1 alone, and remove all spaces in text2.

This could be easy if we didn't have text1, a simple search and replace like this one would do:

%s/\s//g

but in this context I don't know what to do.

I tried with something like:

%s/\(.*|\S*\).\(.*\)/\1\2/g

which works, but removing only the first character, I mean, this should be run on the same line one time for each offending space.

So, a preferred restriction, is to solve this with only one search and replace. And, although I used Vim syntax, use the regular expression flavor you're most comfortable with to answer, I mean, maybe you need some functionality only offered by Perl.

Edit: My solution for Vim:

%s:\(|.*\)\@<=\s::g


One way, in perl:

s/(^.*\||(?=\s))\s*/$1/g

Certainly much greater efficiency is possible if you allow more than just one search and replace.


So you have a string with one pipe (|) in it, and you want to replace only those spaces that don't precede the pipe?

s/\s+(?![^|]*\|)//g


You might try embedding Perl code in a regular expression (using the (?{...}) syntax), which is, however, rather an experimental feature and might not work or even be available in your scenario.

This

s/(.*?\|)(.*)(?{ $x = $2; $x =~ s:\s::g })/$1$x/

should theoretically work, but I got an "Out of memory!" failure, which can be fixed by replacing '\s' with a space:

s/(.*?\|)(.*)(?{ $x = $2; $x =~ s: ::g })/$1$x/
0

精彩评论

暂无评论...
验证码 换一张
取 消