簡體   English   中英

在 2 個字符串之間查找字符串並替換 - 正則表達式

[英]Find String and Replace between 2 Strings - Regular expression

我有一個字符串,我想在其中找到 Description 和之間的所有單詞並替換這些單詞,使它們只有 255 個字符長。 如果單詞少於 255 個字符,則不執行任何操作,如果超過 255 個字符,則截斷單詞。 我使用了一個正則表達式,只有單詞被捕獲在我定義的范圍之外。

我是以下正則表達式:

(?<=<Name>Description<\/Name><Value>)(?<Text>.{0,255}).*?(?=<\/Value>)

代碼為 C#。

我有一個執行以下操作的 C# 腳本:

            string strFile = File.ReadAllText(@"D:\FINAL.xml");
            string pattern = @"(?<=<Name>Description<\/Name><Value>)(?<Text>.{0,255}).*?(?=<\/Value>)";
            string result = Regex.Replace(strFile, pattern, "${Text}");
            File.WriteAllText(@"D:\FINAL.xml", result);

例如: https://regex101.com/r/Etfpol/5

這是一個壞主意,但你的想法,你的電腦,......(一般來說,你不應該使用正則表達式來“解析”xml 或 html,壞事可能發生/將會發生,可能不是今天而是明天或后天)

string pattern = @"(?<=<Name>Description</Name><Value>)([^<]*)(?=</Value>)";
const int maxLength = 255
string result = Regex.Replace(strFile, pattern, x => x.Value.Length > maxLength ? x.Value.Remove(maxLength) : x.Value);

您需要一個MatchEvaluator ,一個接收匹配並計算替換的方法。

嗯...您甚至可以不使用MatchEvaluator ...

string pattern = @"(?<=<Name>Description</Name><Value>)([^<]{0,255})([^<]*)(?=</Value>)";
string result = Regex.Replace(strFile, pattern, "$1");

暫無
暫無

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

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