简体   繁体   中英

Remove Alpha characters from Suffix of string Perl Regex

How can I remove an alpha suffix from a line? Ie

AA12412BB Should return AA12412

basically looking right to left removing any characters after the last numeric character

试试这个: $line =~ s/\\D+\\z//;

If the string is in $_ :

s/\D+?$//;

[EDIT]: Non-greedy matching (the +? ) should be used if the line might end with \\n , to avoid stripping this character (thanks to DanD for pointing this out). This works because $ will match either end-of-string, or immediately before a \\n at end-of-string.

When working with lines of text, it's generally a good idea to first strip off any trailing \\n by calling chomp() , then do whatever work is needed, and finally append a \\n when the line is written out. This simplifies handling suffixes and computing the length of the line, and is useful enough that perl provides the -l option to automate the process for one-liners. In this case, the simpler s/\\D+$//; can be used:

perl -lpe "s/\D+$//" < in.txt > out.txt

Try this:

$str =~ s/(?<=\d)\D+//;

You might want to throw a \\b in there if there are multiple targets in the line:

$str =~ s/(?<=\d)\D+\b//;

If you only want to affect the last match in a line, you can use $ instead:

$str =~ s/(?<=\d)\D+$//;

s/[A-Za-z]{2}$//;

Or if you want a one-liner, type this in at the DOS prompt:

perl -pe "s/[A-Za-z]{2}$//" <a.txt >b.txt

This removes 2 alphabetic characters from the end of every line in a.txt and saves the new data to b.txt

If the line doesn't end in 2 alphabetic characters then the line is not modified. If b.txt doesn't exist already then it is created. If b.txt does exist then any old contents in b.txt is destroyed. a.txt and b.txt need to be in the directory that you are in when you type the one-liner eg if you are in C:\\users when you type in the one-liner than a.txt and b.txt need to also be in C:\\users

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