简体   繁体   中英

perl - using regex to get substring

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?

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM