How to get strings out of a larger string in Perl
I have several conditions that I have stored in a string under the variable $conditions. The string would look something like this
"s(job_name1) or s(job_name2) or s(job_name3) and s(job_name4)"
What I would like to 开发者_开发问答do is just get each job name and sore it in a temporary variable. Right now I have the following, but my gut feeling says that that will not work.
@temp = split(/(s()\ orand)/, $conditions)
Any ideas on how to do this?
It's trivial:
my @names = $conditions =~ /s\(([^)]*)\)/g;
This simple solution assumes that the parenthesized text cannot contain more parentheses, and that nothing like escaping is possible.
Edit: Meant to include this expanded version of the same regex, which might make things a bit clearer:
my @names = $conditions =~ m{
s \( # match a literal s and opening parenthesis
( # then capture in a group
[^)]* # a sequence a zero or more
# non-right-parenthesis characters
)
\) # followed by a literal closing parenthesis
}gx; # and return all of the groups that matched
my @jobnames;
while($conditions =~ m/s\(([^)]*)\)/g) {
push @jobnames, $1;
}
You probably need to do two things:
- Split the input on either
and
oror
- Remove the
s()
bit
Here's one way to do it using split
and then map
:
@temp = map({/s\(([^)]+)\)/} split(/\s+(?:and|or)\s+/, $conditions));
Or slightly more clearly:
# Break apart on "and" or "or"
@parts = split(/\s+(?:and|or)\s+/, $conditions);
# Remove the s() bit
@temp = map({/s\(([^)]+)\)/} @parts);
Assuming no nested parentheses.
$_ = 's(job_name1) or s(job_name2) or s(job_name3) and s(job_name4)';
my @jobs = /\((.+?)\)/g;
print "@jobs\n";
精彩评论