gpt4 book ai didi

c# - 在长文本中使用正则表达式删除字符附近的空格

转载 作者:行者123 更新时间:2023-11-30 20:55:23 25 4
gpt4 key购买 nike

如何删除长文本中字符附近的一个或多个空格。我不想删除不存在于匹配字符串附近的其他空格。我只想删除匹配字符旁边的所有空格,而不是输入字符串的所有空格。例如:

[text][space][space]![space][text]                should result in [text]![text]
[text][space][space]![space][space][space][text] should result in [text]![text]
[text][space]![space][space][text] should result in [text]![text]
[text][space]![space][text] should result in [text]![text]
[text]![space][space][text] should result in [text]![text]
[text][space][space]![text] should result in [text]![text]
[text][space][space]! should result in [text]!
![space][space][text] should result in ![text]

我要写的代码是:

for (int i = 0 to length of string)
{
if (string[i] == character) //which is the desired character "!"
{
int location = i+1;
//remove all whitespace after the character till a non-whitespace character
//is found or string ends
while (string[location] == whitespace)
{
string[location].replace(" ", "");
location++;
}

int location = i-1;
//remove all whitespace before the character till a non-whitespace character
//is found or string ends
while (string[location] == whitespace)
{
string[location].replace(" ", "");
location--;
}
}
}

是否有更好的方法使用 Regex 删除字符附近的空格?

更新:我不想删除不存在于匹配字符串附近的其他空格。例如:

some_text[space]some_other_text[space][space]![space]some_text[space]some_other_text 
is
some_text[space]some_other_text!some_text[space]some_other_text

最佳答案

Regex rgx = new Regex(pattern);
string input = "This is text with far too much " +
"whitespace.";
string pattern = "\\s*!\\s*";
string replacement = "!";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

取自http://msdn.microsoft.com/de-de/library/vstudio/xwewhkd1.aspx

关于c# - 在长文本中使用正则表达式删除字符附近的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18352473/

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