Home: Perl Programming Help: Regular Expressions:
Regular expression with .*



yaronb
stranger

Aug 26, 2001, 12:14 AM


Views: 16736
Regular expression with .*

I am setting a variable this way:

($string)=$other_string=~/(ABC)/;

If "ABC" exists in $other_string , then $string will equal "ABC".

Now, I want to include in $string the 10 letters before and after ABC.

I tried
($string)=$other_string=~/(.*{10}ABC.*{10})/;

but it doesn't work.

What is the right way to do it ?

Thanks,
Yaron.



mhx
Enthusiast

Aug 26, 2001, 1:52 AM


Views: 16734
Re: Regular expression with .*

You almost had it. Wink Just leave the * out of the regex:

Code
($string)=$other_string=~/(.{10}ABC.{10})/;

The {10} is a quantifier, just as is the *. Keep in mind that the above regex will only match if there are at least 10 characters before and after ABC in $other_string. If you'd like it to match even with less than 10 characters, but match at most 10 characters, use this:

Code
($string)=$other_string=~/(.{0,10}ABC.{0,10})/;

Hope this helps.

-- Marcus


Code
s$$ab21b8d15c3d97bd6317286d$;$"=547269736;split'i',join$,,map{chr(($*+= 
($">>=1)&1?-hex:hex)+0140)}/./g;$"=chr$";s;.;\u$&;for@_[0,2];print"@_,"



dsb
stranger

Apr 11, 2002, 7:19 PM


Views: 16680
Re: [yaronb] Regular expression with .*

FYI,

'.*' in general is not a good idea(there are those that are very passionate about this subject). This construct is greedy and is usually an inefficient(i.e., slow) way of matching. Generally there is a more efficient way of quantifying without using dot-star which also gives more control what the regex will match.

_______________________

dsb
PerlGuy


Paul
Enthusiast

Apr 14, 2002, 4:55 AM


Views: 16676
Re: [dsb] Regular expression with .*

Greedy:

.*

Not greedy:

.*?