簡體   English   中英

從Perl中的字符串中刪除字符和數字

[英]Remove characters and numbers from a string in perl

我正在嘗試重命名目錄中的一堆文件,並且卡在了它的正則表達式部分。

我想從文件名中刪除出現在開頭的某些字符。

_00-author--book_revision_ 1: _00-author--book_revision_

預期: Author - Book (Revision)

到目前為止,我已經可以使用正則表達式刪除下划線並首字母大寫

$newfile =~ s/_/ /g;
$newfile =~ s/^[0-9]//g;
$newfile =~ s/^[0-9]//g;
$newfile =~ s/^-//g;
$newfile = ucfirst($newfile);

這不是一個好方法。 在刪除所有字符之前,我需要幫助,直到您擊中第一個字母,並且當您擊中第一個“-”時,我想在“-”之前和之后添加一個空格。 另外,當我按下第二個'-'時,我想將其替換為'('。

非常感謝您采取正確方法的任何指導,技巧甚至建議。

您的說明和示例不匹配。

根據您的指示,

s/^[^\pL]+//;    # Remove everything until first letter.
s/-/ - /;        # Replace first "-" with " - "
s/-[^-]*\K-/(/;  # Replace second "-" with "("

根據您的示例,

s/^[^\pL]+//;
s/--/ - /;
s/_/ (/;
s/_/)/;
s/(?<!\pL)(\pL)/\U$1/g;
$filename =~ s,^_\d+-(.*?)--(.*?)_(.*?)_$,\u\1 - \u\2 (\u\3),;

我的Perl解釋器(使用嚴格和警告)說,最好這樣寫:

$filename =~ s,^_\d+-(.*?)--(.*?)_(.*?)_$,\u$1 - \u$2 (\u$3),;

第一個可能更喜歡它的味道! (當然,兩個版本的工作原理相同。)

說明(按stema的要求):

$filename =~ s/
  ^       # matches the start of the line
  _\d+-   # matches an underscore, one or more digits and a hypen minus
  (.*?)-- # matches (non-greedyly) anything before two consecutive hypen-minus
          #   and captures the entire match (as the first capture group)
  (.*?)_  # matches (non-greedyly) anything before a single underscore and
          #  captures the entire match (as the second capture group)
  (.*?)_  # does the same as the one before (but captures the match as the
          #  third capture group obviously)
  $       # matches the end of the line
/\u$1 - \u$2 (\u$3)/x;

替換規范中的\\u${1..3}僅告訴Perl將捕獲組從1到3插入,它們的第一個字符大寫。 如果要使整個匹配(在捕獲的組中)大寫,則必須改用\\U

x標志打開了詳細模式,該模式告訴Perl解釋器我們要使用注釋,因此它將忽略這些注釋(以及正則表達式中的任何空格-因此,如果要匹配空格 ,則必須使用\\s\\ )。 不幸的是,我無法弄清楚如何讓Perl忽略*替換*規范中的空白-這就是為什么我在一行上編寫了空白。

(另請注意,我已經改變了我的s終止從,/ - Perl的咆哮在我,如果我用了,用詳細模式開啟...不知道是什么原因。)

那么,您是要大寫新文件名的所有組成部分還是僅將第一個大寫? 您的問題在這一點上是不一致的。

請注意,如果您使用的是Linux,則可能有rename命令,該命令將使用perl表達式並使用它為您重命名文件,如下所示:

rename 'my ($a,$b,$r);$_ = "$a - $b ($r)" 
  if ($a, $b, $r) = map { ucfirst $_ } /^_\d+-(.*?)--(.*?)_(.*?)_$/' _*

如果它們都遵循該格式,請嘗試:

my ($author, $book, $revision) = $newfiles =~ /-(.*?)--(.*?)_(.*?)_/;

print ucfirst($author ) . " - $book ($revision)\n";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM