2

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?

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.