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

Perl regex match

by Eshan_k (Acolyte)
on Feb 11, 2015 at 03:14 UTC ( [id://1116271]=perlquestion: print w/replies, xml ) Need Help??

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

Hello Monks,

I want to match only words like "abcunit", "hedhdunit", "ewedfunit" and get into array from a text file using regex. Can any one please tell how can I get only that word in line. So for I am using /(....unit)/g but the charcters before "unit" are varying. Can any one please tell perfect regex for this. Any help will be greatly appreciated.

unit : abcunit unit : hedhdunit unit : ewedfunit unit : eedunit

Replies are listed 'Best First'.
Re: Perl regex match
by LanX (Saint) on Feb 11, 2015 at 03:22 UTC
Re: Perl regex match
by manoj_speed (Prior) on Feb 11, 2015 at 07:14 UTC
    As LanX mentioned, you can use \w+ to match any word character before 'unit' keyword.

    Just check the code below:

    Code
    # Consider I parsed a file and stored content into below array.
    my @arr=('line 1 abcunit', 'line 2hedhdunit', 'line 3 ewedfunit', 'line 4 eedunit', 'line 5 abdunited');

    for my $str(@arr) { print "Unit : $& \n" if ($str =~ m/\w+unit\b/); }

    # \w+ -> To match any word character before pattern 'unit'
    # \b -> to match the exact word ends with 'unit'.

    Output:
    Unit : abcunit
    Unit : 2hedhdunit
    Unit : ewedfunit
    Unit : eedunit

    -- The wisest mind has something yet to learn...
Re: Perl regex match
by Discipulus (Canon) on Feb 11, 2015 at 09:42 UTC
Re: Perl regex match
by Anonymous Monk on Feb 11, 2015 at 03:19 UTC

    So for I am using /(....unit)/g but the charcters before "unit" are varying.

    Ask yourself what characters? Then make your regex more specific, see perlrequick and perlrebackslash

Log In?
Username:
Password:

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

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

    No recent polls found