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


Hi Monks

i am new to RE.So i try some example.plz help me on this

I have a line like
samir: 23 yearold
so want to retrive only the samir: 23 from that line

Replies are listed 'Best First'.
Re: Find the word????
by cdarke (Prior) on Oct 11, 2006 at 09:00 UTC
    When you first start with REs it looks like the difficulty is in learning the meta-language. Actually that is the easy part, the most difficult part of using REs is in understanding your data.
    For example, "samir: 23 yearold". Is the name always at the start of text and preceeded by a colon ':'? Is there always a space before and after the age? Is the age always 2 characters, or between 1 and 3 digits? And so on.
    To extract text from an RE you can use a "capturing parenthesis group", which just means that the pattern described in rounded brackets are saved into special variables, the first going into $1, second into $2, and so on. I suggest you go through perlretut.
    There are many solutions to your question, mine would be:
    my $s = 'samir: 23 yearold'; $s =~ /^(.*: \d+)/; my $NameAge = $1; print "$NameAge\n";
Re: Find the word????
by davorg (Chancellor) on Oct 11, 2006 at 09:01 UTC

    You need to be clearer about the rules that define what you actually want to extract from the line. For example, this does what you asked, but almost certainly isn't what you want:

    $_ = 'samir: 23 yearold'; my $match $match = $1 if /(samir: 23)/;

    Maybe you want something more like this:

    $_ = 'samir: 23 yearold'; my $match $match = $1 if /(\w+:\s+\d+)/;

    But without knowing what your rules are, there's no way we can really help.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Find the word????
by lima1 (Curate) on Oct 11, 2006 at 08:43 UTC
    we must know how the other lines look like.
    $s = "samir: 23 yearold"; $s =~ m{(.*) \s yearold \z}xms; print $1
    would for example fetch everything before " yearold" (at the end of the string);
Re: Find the word????
by GrandFather (Saint) on Oct 11, 2006 at 08:52 UTC