PDA

View Full Version : RegEx question


super_gunda
08-03-2007, 10:23 PM
HI,

I have a string as follows:

$a = "1. '-Mt 5'"
2. '-df 48'

so my $a will have <doubleQuote>1. '-Mt 5'<doubleQuote>

I am trying to get a regex that gives me only stuff in single quotes.
I am not able to get hold of efficient solution.
Could any of you suggest one?

Thanks,
R

super_gunda
08-03-2007, 11:21 PM
I mean...what is the regex to match anything between two single quotes?
The string has two single quotes too.

Thanks!

javabits
08-04-2007, 12:51 AM
This should match the string in between the single quotes.


$a = "1. '-Mt 5'";
$a =~ /('.+')/;
print $1


semper fi...

FishMonger
08-04-2007, 12:51 AM
$a = "1. '-Mt 5'";

($b) = $a =~ /'(.+?)'/;

print $b;

FishMonger
08-04-2007, 12:58 AM
This should match the string in between the single quotes.


$a = "1. '-Mt 5'";
$a =~ /('.+')/;
print $1


It also captures the single quotes in addition to the string in between the single quotes. If there are multiple "sets" of single quotes, it will capture everything from the first to the last single quote.

$a = "1. '-Mt 5' and 2. '-df 48'";
$a =~ /('.+')/;
print $1;

Outputs:
'-Mt 5' and 2. '-df 48'

javabits
08-07-2007, 12:39 AM
Hmm...you're right about that. A modification to the regex would be needed if there are going to be multiple items in single quotes.

The below should work in most cases.

semper fi...


$a = "1. '-Mt 5' and 2. '-df 48'";
while ($a =~ /('[^']+')/g) {
print "$1\n";
}

javabits
08-07-2007, 12:46 AM
You can have the regex return the results in an array too.


$a = "1. '-Mt 5' and 2. '-df 48'";
@items = $a =~ /('[^']+')/g;

foreach (@items) {
print "$_\n";
}


semper fi...

FishMonger
08-07-2007, 07:09 AM
Well, if you're going to use a while of for loop to execute a single expression, then it would be easier to go this route.

my $a = "1. '-Mt 5' and 2. '-df 48'";

print "$_\n" for $a =~ /('[^']+')/g;

# or
print map {"$_\n"} $a =~ /('[^']+')/g;