Newbie: Regular expresion

J

Jose Luis

Hi,

Given the string "one;two;three;four...", is there a easy way to
print "one":


$ echo "one;two;three;four..."|perl -e 'while(<>){$_ =~ /^(.*)(\;)(.*)
$/ && print $1}'
one;two;three



Thanks in advance,
Jose Luis
 
J

Jürgen Exner

Jose Luis said:
Given the string "one;two;three;four...", is there a easy way to
print "one":

use strict; use warnings;
my $s = "one;two;three;four...";
print ((split(/;/, $s))[0]);

jue
 
P

Peter Makholm

Jose Luis said:
Given the string "one;two;three;four...", is there a easy way to
print "one":

Not using regular expressions I would use the split function to
archieve this.
$ echo "one;two;three;four..."|perl -e 'while(<>){$_ =~ /^(.*)(\;)(.*)
$/ && print $1}'
one;two;three

But what you are missing is the non-greedy variant of the initial
*. By default quantifiers af greedy, that is that they match as much
as posible. If you instead uses (.*?) it will match as little as
posible.

Another soulution woulb be to replace (.*) with ([^;]*). This matches
as many non-semicolon as possible.

//Makholm
 
J

Jürgen Exner

Peter Makholm said:
Not using regular expressions I would use the split function to
archieve this.

Actually the first argument to split() is a regular expression.
But I do strongly share your sentiment about using split() for this task
instead of capturing RE groups.

jue
 
S

Steve C

Jose said:
Hi,

Given the string "one;two;three;four...", is there a easy way to
print "one":


$ echo "one;two;three;four..."|perl -e 'while(<>){$_ =~ /^(.*)(\;)(.*)
$/ && print $1}'
one;two;three

Use 'sed mode':

echo "one;two;three;four..."|perl -pe 's/;.*//'
one

autosplit lets you pick other than first element:

echo "one;two;three;four..."|perl -lanF';' -e'print $F[1]'
two
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top