Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Regex, query

by dmsparts (Sexton)
on Jan 24, 2013 at 15:48 UTC ( [id://1015188]=perlquestion: print w/replies, xml ) Need Help??

dmsparts has asked for the wisdom of the Perl Monks concerning the following question:

HI,

i am trying to create a variable which contains a reference number matched from within a text string.

example,

textstring = Michael please look at E123456

where E123456 is a reference number i need to look at. i want this reference number to be added to a variable called $lookatref. The string is always in the same format, NAME please look at REF. The ref can be either one letter followed by 6 numbers or just 7 numbers

the code im using is

$lookatref = ""; $mystring2 = 'please look at '; if ($reqtext =~ m/$mystring2(.*?) /i) {$lookatref = $1;}

$reqtext is the text i want to match. this is read into the variable earlier in the script. i think it is something to do with the regex syntax, but i just cant figure out what it wrong.

Replies are listed 'Best First'.
Re: Regex, query
by Ratazong (Monsignor) on Jan 24, 2013 at 15:55 UTC

    It works for me. Are you sure there is a whitespace after E123456? If you are sure that the REF is the last element in the input, you might want to use a greedy capture instead: change  (.*?) to  (.*)

    Alternatively, you could append a whitespace to your input before applying the regex ($reqtext .= " ";)

    HTH, Rata

      Thanks. adding the whitespace at the end did the trick.

Re: Regex, query
by SuicideJunkie (Vicar) on Jan 24, 2013 at 15:57 UTC

    The non-greedy .*? will happily match zero characters and quit if it can.

    Why not have it capture the thing you're looking for ([a-z]?[0-9]{6,7}) instead?

Re: Regex, query
by kennethk (Abbot) on Jan 24, 2013 at 16:03 UTC

    Assuming your input string is 'Michael please look at E123456', your regular expression expects a trailing space that is not there. Rather than looking for trailing white space, perhaps you'd like the non-whitespace character class \S (m/$mystring2\s*(\S*)/i)? See Using character classes.


    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1015188]
Approved by Ratazong
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-16 16:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found