簡體   English   中英

正則表達式的C#問題

[英]C# Trouble with Regex.Replace

整天都在為這個問題撓頭!

好的,所以我有一個包含以下內容的字符串:

?\"width=\"1\"height=\"1\"border=\"0\"style=\"display:none;\">');

我想將該字符串轉換為以下內容:

?\"width=1height=1border=0style=\"display:none;\">');

從理論上講,我可以在“ \\” 1 \\“”等上執行String.Replace。但這並不是一個切實可行的選擇,因為該字符串理論上可以在表達式中包含任何數字。

我還考慮過刪除字符串“ \\”“,但是還有其他一些我不想替換的情況。

我一直在嘗試使用Regex.Replace方法,因為我相信這種方法可以解決我的問題。 這是我得到的:

chunkContents = Regex.Replace(chunkContents, "\".\"", ".");

現在,這確實使事情搞砸了(它替換了正確的元素,但有句號),但是我認為您可以看到我正在嘗試做的事情。 我還擔心這僅適用於單個數字(\\“ 1 \\”而不是\\“ 11 \\”)。因此,這使我開始考慮使用“ *”或“ +”表達式而不是“。”。 ,但是我預見到了這樣一個問題,即會在所需字符(到處都是點綴)之間拾取所有文本,而我顯然只想將它們之間的數字字符替換掉。

希望我已經解釋清楚了,如果需要的話,很樂意提供任何額外的信息:)

嘗試這個

var str = "?\"width=\"1\"height=\"1234\"border=\"0\"style=\"display:none;\">');";
str = Regex.Replace(str , "\"(\\d+)\"", "$1");

(\\\\d+)是一個捕獲組,用於查找一個或多個數字,$ 1引用捕獲的組。

這有效

String input = @"?\""width=\""1\""height=\""1\""border=\""0\""style=\""display:none;\"">');";

//replace the entire match of the regex with only what's captured (the number)
String result = Regex.Replace(input, @"\\""(\d+)\\""", match => match.Result("$1"));

//control string for excpected result
String shouldBe = @"?\""width=1height=1border=0style=\""display:none;\"">');";

//prints true
Console.WriteLine(result.Equals(shouldBe).ToString());

暫無
暫無

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

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