简体   繁体   中英

How can i remove a substring using regexp in Perl?

Given a file containing multiple strings (one in each line) - among them there will be the following two strings:

de12_QA_IR_OS_HV
de12_IR_OS_HV

(the only difference is "QA_" in the right position).

I need to perform some action if the current line being handled contains one of the above. if yes, i should use the string value without the "QA_" substring.

I am using the following regexp to detect the values /de12_(QA_)?IR_OS_HV/ but is there a way to remove the "QA_" if it exist using the same regexp ?

You can capture what's before and after the QA_:

if (/(de12_)(QA_)?(IR_OS_HV)/) {
    print $1 . $3, "\n";

Or, use substitution

if (s/de12_(QA_)?IR_OS_HV/de12_IR_OS_HV/) {
    print $_, "\n";
}

But, in fact, you know what string to use if you the regex matches:

if (/de12_(QA_)?IR_OS_HV/) {
    print "de12_IR_OS_HV\n";
}

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