简体   繁体   English

在 2 个字符串之间查找字符串并替换 - 正则表达式

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

I have a string that I would like to find within it all the words between Description and and replace the words so that they are just 255 characters long.我有一个字符串,我想在其中找到 Description 和之间的所有单词并替换这些单词,使它们只有 255 个字符长。 If the words are less than 255 characters it does nothing, if it is more than 255 characters it is to truncate the words.如果单词少于 255 个字符,则不执行任何操作,如果超过 255 个字符,则截断单词。 I used a regular expression, only words are caught outside the range defined by me.我使用了一个正则表达式,只有单词被捕获在我定义的范围之外。

I am the folowing regular expression:我是以下正则表达式:

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

The code is C#.代码为 C#。

I have a C# script that does the folowing:我有一个执行以下操作的 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);

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

It is a bad idea, but your idea, your pc, ... (in general you shouldn't use Regexes to "parse" xml or html, bad things could happen/will happen, perhaps not today but tomorrow or the day after)这是一个坏主意,但你的想法,你的电脑,......(一般来说,你不应该使用正则表达式来“解析”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);

You need a MatchEvaluator , a method that receives the match and calculates a replacement.您需要一个MatchEvaluator ,一个接收匹配并计算替换的方法。

Mmmh... You can even do without a 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