Feng Guo
Feng Guo

Reputation: 11

How to extract a set of number from a string after a "triggering word"

I'm a beginner to Perl and Regular Expression. I want to extract certain amount dollar after $. So I write the following code. However, I try to avoid the first $ sign, that is, I only want the information after word "My" in this case.

my $str = 'His house is small; only worth $90,000;My house is so big; it worth $179,000; ';
if ( $str =~ /\$([\d,]+)/) {
my $used = $1;
print "House Price: $used\n";
}

Any help would be appreciated.

Upvotes: 1

Views: 60

Answers (3)

Abhijeet Kasurde
Abhijeet Kasurde

Reputation: 4127

my $str = 'His house is small; only worth $90,000;My house is so big; it worth $179,000; ';
if ( $str =~ /My.*?\$(\d+,\d+)?/) {
    my $used = $1;
    print "House Price: $used\n";
}

House Price: 179,000

Upvotes: 1

ndnenkov
ndnenkov

Reputation: 36100

My.*?\K\$\d+(,\d+)?

See it in action


The idea is:

  • My - find My
  • .*? - match the least amount of characters until you get to a $ sign
  • \K - drop everything matched so far (so it's not included in the result)
  • \$\d+(,\d+)? - support either integers or float amount of $s

Upvotes: 1

vks
vks

Reputation: 67968

^.*\bMy\b(*SKIP)(*F)|\$([\d,]+)

You can use (*SKIP)(*F) here.See demo.

https://regex101.com/r/fM9lY3/52

Upvotes: 1

Related Questions