-1

Could somebody explain to me, why this is not working:

# echo '"Hello,1" "Hello,2" "Hello,3"' | perl -pe 's/".+?,3"/1/'
1

or

# echo '"Hello,1" "Hello,2" "Hello,3"' | perl -pe 's/".+?,2"/1/'
1 "Hello,3"

My intention was to replace/find only "Hello,3"/"Hello,2", but It seems that the non-greedy modifier (or my brain) is not working as expected.

Dan
  • 33
  • 3

2 Answers2

2

I think you're misunderstanding regular expressions, but actually I'd probably suggest tackling this one a bit differently. If you've a sequence of words to manipulate, I'd suggest using split/join/map to do the manipulation.

I think it scales better, and doesn't trip over on clarity problems with where the pattern matching boundaries lie.

Something like this:

my $str = '"Hello,1" "Hello,2" "Hello,3"';

$str = join ( " ", map { s/Hello,[23]/1/r } split ( " ", $str ) );
print $str;

Or as a one liner:

perl -ape "/Hello/ and $_ = join ' ', map { s/Hello,[23]/1/r } @F"
Sobrique
  • 52,974
  • 7
  • 60
  • 101
1

Try this

/"[^"]+,3"/

instead. https://regex101.com/r/4rXN4z/1

Narrative

ceving
  • 21,900
  • 13
  • 104
  • 178
Fallenhero
  • 1,563
  • 1
  • 8
  • 17