How can I extract a substring up to the first digit?

后端 未结 4 1160
名媛妹妹
名媛妹妹 2021-01-15 09:01

How can I find the first substring until I find the first digit?

Example:

my $string = \'AAAA_BBBB_12_13_14\' ;

Result expected: \'AAA

4条回答
  •  时光取名叫无心
    2021-01-15 09:15

    Judging from the tags you want to use a regular expression. So let's build this up.

    • We want to match from the beginning of the string so we anchor with a ^ metacharacter at the beginning
    • We want to match anything but digits so we look at the character classes and find out this is \D
    • We want 1 or more of these so we use the + quantifier which means 1 or more of the previous part of the pattern.

    This gives us the following regular expression:

    ^\D+
    

    Which we can use in code like so:

    my $string = 'AAAA_BBBB_12_13_14';
    $string =~ /^\D+/;
    my $result = $&;
    

提交回复
热议问题