Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

(wil) Re: regex: extract a substring

by wil (Priest)
on May 23, 2002 at 20:38 UTC ( [id://168895]=note: print w/replies, xml ) Need Help??


in reply to regex: extract a substring

If you're sure that that is going to be your string every time, then something like this should work:
$foo = "abchelloxyz"; $foo =~ s/abc([\w]+)xyz/$1/;

However, if your input is going to be different, i.e. use something other than (in my example) any alphanumeric character, then your regex is going to be slightly different too.

Posting some sample data would help in building up a regex for you.

- wil

Replies are listed 'Best First'.
Re: (wil) Re: regex: extract a substring
by krujos (Curate) on May 23, 2002 at 21:28 UTC
    Do keep in mind that wil's example will make foo equal to the characters between abc and xyz. i.e. $foo == "hello" if you are trying to extract to another variable you need to do something more like this.
    $foo = "abchelloxyz"; $foo =~ /abc([\w]+)xyz/; $bar = $1;

    the value of $foo is unchanged. ---Mogaka is good
      $foo =~ /abc([\w]+)xyz/; $bar = $1;

      or in one line:

      ($bar) = /abc([\w]+)xyz/;

      From perlop:

      If the /g option is not used, m// in a list context returns a list consisting of the subexpressions matched by the parentheses in the pattern, i.e., ($1, $2, $3...). (Note that here $1 etc. are also set, and that this differs from Perl 4's behavior.) When there are no parentheses in the pattern, the return value is the list (1) for success. With or without parentheses, an empty list is returned upon failure.

      -- Hofmator

      en passant:
      $foo='abchelloxyz'; ($bar=$foo)=~s/abc(\w+)xyz/\1/;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (7)
As of 2024-04-25 11:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found