How can I extract substrings from a string in Perl

2020-06-09 01:09发布

Consider the following strings:

1) Scheme ID: abc-456-hu5t10 (High priority) *****

2) Scheme ID: frt-78f-hj542w (Balanced)

3) Scheme ID: 23f-f974-nm54w (super formula run) *****

and so on in the above format - the parts in bold are changes across the strings.

==> Imagine I've many strings of format Shown above. I want to pick 3 substrings (As shown in BOLD below) from the each of the above strings.

  • 1st substring containing the alphanumeric value (in eg above it's "abc-456-hu5t10")
  • 2nd substring containing the word (in eg above it's "High priority")
  • 3rd substring containing * (IF * is present at the end of the string ELSE leave it )

How do I pick these 3 substrings from each string shown above? I know it can be done using regular expressions in Perl... Can you help with this?

7条回答
▲ chillily
2楼-- · 2020-06-09 01:59

This just requires a small change to my last answer:

my ($guid, $scheme, $star) = $line =~ m{
    The [ ] Scheme [ ] GUID: [ ]
    ([a-zA-Z0-9-]+)          #capture the guid
    [ ]
    \(  (.+)  \)             #capture the scheme 
    (?:
        [ ]
        ([*])                #capture the star 
    )?                       #if it exists
}x;
查看更多
登录 后发表回答