我需要一個寄存器例腳本正則表達式替換
- 刪除所有符號
- 允許最多1個連字符彼此連接
- 允許最大1個週期總
例如:
- Mike & Ike 輸出是:MikeIke
- MikeIke 輸出是:MikeIke
- MikeIke-吉爾輸出是:MikeIke-吉爾
- MikeIke-吉爾輸出是:麥克 - 艾克 - 吉爾
- 邁克 - 艾克 - 吉爾輸出是:邁克 - 艾克 - 吉爾
- Mike.Ike.Bill 輸出爲:Mike.IkeBill
- 邁克***喬輸出爲:MikeJoe
- Mike123 輸出爲:Mike123
我需要一個寄存器例腳本正則表達式替換
例如:
你可以做若干遍的東西。
這是一種通用的解決方法,可以通過使用lookbehind縮短。
與正則表達式(不是所有的正則表達式的口味不支持此)
-
-{2,}
-.
與正則表達式[^-\.A-Za-z0-9]
.
與一個臨時字符例如!
和替換剩餘.
.
更新從最後一步更換!
(我不是一個C#程序員,用這種regex tester這reference爲C# .net正則表達式的味道。)
String str = "Mike&Ike ......";
str = Regex.Replace(str, @"-+", @"-");
str = Regex.Replace(str, @"(?<=\.)(.*?)\.", @"$1");
str = Regex.Replace(str, @"[^\w\r\n]", @"");
-
單-
.
如果使用positiv回顧後(?<=...)
\w
是短期的不是第.
[A-Za-z0-9]
我需要它在C#.Net – Jigar 2011-03-29 17:39:17
#!/usr/bin/env perl
use 5.10.0;
use strict;
use warnings;
my @samples = (
"Mike&Ike" => "MikeIke",
"Mike-Ike" => "Mike-Ike",
"Mike-Ike-Jill" => "Mike-Ike-Jill",
"Mike--Ike-Jill" => "Mike-Ike-Jill",
"Mike--Ike---Jill" => "Mike-Ike-Jill",
"Mike.Ike.Bill" => "Mike.IkeBill",
"Mike***Joe" => "MikeJoe",
"Mike123" => "Mike123",
);
while (my($got, $want) = splice(@samples, 0, 2)) {
my $had = $got;
for ($got) {
# 1) Allow max 1 dashy bit connected to each other.
s/ (\p{Dash}) \p{Dash}+ /$1/xg;
# 2) Allow max 1 period, total.
1 while s/^[^.]* \. [^.]* \K \. //x ;
# 3) Remove all symbols...
s/ (?! [\p{Dash}.]) [\p{Symbol}\p{Punctuation}] //xg ;
# ...and punctuation
# except for dashy bits and dots.
}
if ($got eq $want) { print "RIGHT" }
else { print "WRONG" }
print ":\thad\t<$had>\n\twanted\t<$want>\n\tgot\t<$got>\n";
}
生成:
RIGHT: had <Mike&Ike>
wanted <MikeIke>
got <MikeIke>
RIGHT: had <Mike-Ike>
wanted <Mike-Ike>
got <Mike-Ike>
RIGHT: had <Mike-Ike-Jill>
wanted <Mike-Ike-Jill>
got <Mike-Ike-Jill>
RIGHT: had <Mike--Ike-Jill>
wanted <Mike-Ike-Jill>
got <Mike-Ike-Jill>
RIGHT: had <Mike--Ike---Jill>
wanted <Mike-Ike-Jill>
got <Mike-Ike-Jill>
RIGHT: had <Mike.Ike.Bill>
wanted <Mike.IkeBill>
got <Mike.IkeBill>
RIGHT: had <Mike***Joe>
wanted <MikeJoe>
got <MikeJoe>
RIGHT: had <Mike123>
wanted <Mike123>
got <Mike123>
嘿,湯姆,那是什麼'\ K'? (無法在MRE3中找到它) – ridgerunner 2011-03-28 22:46:01
@ridgerunner:'\ K'是**「保留」**到目前爲止所匹配的所有內容的一種方式。這是一個額外捕獲組和僞替換的捷徑。 – tchrist 2011-03-28 22:57:51
@Tom:很感謝。看起來我將不得不坐下來學習Perl - (在那裏有很多正則表達式......)有沒有一本你可以推薦的好書? (我有你的駱駝書第三版,但它已超過10歲)我越來越老,只能適應這麼多語言進入我的(褪色)大腦!再次感謝。 – ridgerunner 2011-03-28 23:17:50
你可以把一些精力來修復你的問題?你的要求奇怪地分散。我想我可以猜出你的意思,但你應該是修復它的人。您可以使用問題下方的[編輯鏈接](http://stackoverflow.com/posts/5463310/edit)。 – 2011-03-28 18:33:30
在第六個例子中給出'Mike.lkeBill'的規則是什麼? – sawa 2011-03-28 18:44:39
'允許最多1個週期總計'可能需要某種類型的lookbehind或lookahead,這是所有正則表達式不支持的。請指定您正在使用的語言。 – 2011-03-28 20:42:32