Reputation: 3337
I do realize that there are a lot of perl regex questions here on SO; I haven't been able to find one that helps me in my situation. I have the following string:
string = "dn: example\nl: example\ndepartment: example\nname: example"
I am trying to extract each field (except dn) using the following:
my ($name) = $output_string =~ /name:\s(\w+)\n/;
my ($department) = $output_string =~ /department:\s(\w+)\n/;
my ($location) = $output_string =~ /location:\s(\w+)\n/;
I must not be understanding how to use regex, because that isn't working for me. Each variable is ending up undefined. What am I doing wrong?
Upvotes: 2
Views: 1853
Reputation: 98508
The problem here is your input; you are expecting a \n
after name:
but there isn't one there, and you are looking for location:
but have l:
in your input.
Using the /m
flag and $
instead of \n
will fix the first problem, because $
will match at either the end of a line or the end of the input.
Upvotes: 1
Reputation: 5973
Add the m
flag to switch on multi-line mode, then use start-of-line and end-of-line anchors to match the start/end of the lines in your string:
my ($name) = $output_string =~ /^name:\s(\w+)$/m;
my ($department) = $output_string =~ /^department:\s(\w+)$/m;
my ($location) = $output_string =~ /^location:\s(\w+)$/m;
Upvotes: 2