Håkon Hægland
Håkon Hægland

Reputation: 40778

Match text up to given character but excluding character occurrence within single quotes in Perl

I am trying to extract text from a string up to the next occurrence of a /, not counting slashes that occur within single quotes. For example

my $str="test 'a/b' c/ xxx /";
$str =~ /(.*?)\//;
print "$1\n";

gives

test 'a

whereas I would like to get:

test 'a/b' c

Upvotes: 2

Views: 80

Answers (4)

TLP
TLP

Reputation: 67900

Text::ParseWords can handle quoted delimiters:

use strict;
use warnings;
use Text::ParseWords;

my $str = "test 'a/b' c/ xxx /";
my ($first) = quotewords('/', 1, $str);
print $first;

Output:

test 'a/b' c

Upvotes: 4

Miller
Miller

Reputation: 35208

my $str="test 'a/b' c/ xxx /";

$str =~ m{^((?>[^'/]+|'[^']*')*)/};

print $1;

Or if strings can contain escaped single quotes:

$str =~ m{^((?>[^'/]+|'(?>[^'\\]+|\\.)*')*)/}x;

Upvotes: 3

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89584

you can try this:

$str =~ /^((?>[^'\/]+|'[^']*')*)\//;

Upvotes: 4

dabi
dabi

Reputation: 131

If your string data is always "A/B/" then you could use the following:

#!/usr/bin/perl -w

my $str = "test 'a/b' c/ xxx /";
$str =~ m/(.*)\/(.*)\/$/;
print "$1\n";

Upvotes: 0

Related Questions