gpt4 book ai didi

c# - 删除前导尾随空格

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:06 24 4
gpt4 key购买 nike

我正在阅读包含以下内容的文本文件中的内容

    <ID> test data </Id> <Sub_Tab> test data </sub_tab> <form> form data </form>

我的要求是我在 ID 和 Sub_tab 标签中拥有的任何内容我想从这些标签内的内容中删除尾随和前导空格,但 form 标签内的内容应该保持不变。我的输出应该是:

    <iD>test data</Id> <Sub_Tab>test data</sub_tab> <form> form data </form>

尝试了很多模式,但都没有用

Regex regex = new Regex(@"/>[ \t]+</");
string newContent = regex.Replace(fileContent, "><");

最佳答案

这种感觉有点矫枉过正。可能是因为太矫枉过正了?
无论如何,您可以使用正则表达式轻松地做到这一点。但是此时,我对正则表达式还不熟悉。
所以,这是我对你的问题的解决方案。它来了。

string input = "<ID> test data </Id> <Sub_Tab> test data </sub_tab> <form> form data </form>";

string find = "ƸƷ";
// ƸƷ - If you have these two characters in your input string, then this won't work.
// These characters (ƸƷ) can be replaced with any unique string. However, this function
// to work, that string should not be contained in the input string
// or it will mess the replace function. This can be done without using
// these characters. But it might require more coding. So, I'm going with this.
string str = input;

IList < string > strList = new List < string > ();

// Remove all content inside the form tags
while (true) {
if ((str.Contains("<form>")) && (str.Contains("</form>"))) {
int start = str.IndexOf("<form>");
int end = str.IndexOf("</form>");

string result = str.Substring(start, end - start + 7); // 7 = "</form>".Length
str = str.Replace(result, find);
strList.Add(result);
} else {
break;
}
}

// Manipulate the data
str = str.Replace(" <", "<").Replace("> ", ">");

// Add the contents inside the form tags
foreach(string val in strList) {
int place = str.IndexOf(find);
str = str.Remove(place, find.Length).Insert(place, val);
}

Console.WriteLine("Input String: " + input);
Console.WriteLine("Output String: " + str);

例子01

<ID> test data </Id> <Sub_Tab> test data </sub_tab> <form> form data </form> 
<ID>test data</Id><Sub_Tab>test data</sub_tab><form> form data </form>

例子02

<ID> test data </Id> <Sub_Tab> test data </sub_tab> <form> form data <div> data </div> </form> <br>
<ID>test data</Id><Sub_Tab>test data</sub_tab><form> form data <div> data </div> </form><br>

例子03

<ID> test data </Id> <form> <span> date </span> </form> <Sub_Tab> test data </sub_tab> <form> form data </form>
<ID>test data</Id><form> <span> date </span> </form><Sub_Tab>test data</sub_tab><form> form data </form>

在线演示:https://rextester.com/FZU31740

关于c# - 删除前导尾随空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57412932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com