【问题标题】:Replace certain string if it has a matching string after it?如果某个字符串后面有匹配的字符串,则替换它?
【发布时间】:2014-03-06 10:52:04
【问题描述】:

我有一个这样的字符串:

this'is'my'
test'
string'

我需要在 '.

上使用正则表达式进行查找和替换

我需要把'换成'\r\n,而不是改变已经有行距的其他行,基本上是这样的:

this'
is'
my'
test'
string'

我不能删除所有的“\r\n”然后全部更改,因为我需要快速并且只更改需要更改的内容。

目前我正在这样做:

var EscapeCharactor = "?"
var LineEndCharactor = "'"

string result = Regex.Replace(data, @"(([^\" + EscapeCharactor + "]" + LineEndCharactor + @"[^\r\n|^\r|^\n])|(\" + EscapeCharactor + @"\" + EscapeCharactor + LineEndCharactor + "[^\r\n|^\r|^\n]))", "$1\r\n");
return ediDataUnWrapped;

但它正在创造这个:

this'i
s'm
y'
test'
string'

这是否可能只更改某些而不包含额外的字母,还是我必须通过删除所有 \r\n 来管理,然后将其添加到所有这些?

【问题讨论】:

  • 最好重命名 char 变量。令人困惑。
  • 我的代码命名正确,我只是为示例做了这个,但我也会更改它,以便阅读它的人更有意义。

标签: c# regex replace


【解决方案1】:

这是一种非正则表达式方法:

string testString = @"this'is'my'
test'
string'";

var split = testString.Split(new[]{"'"}, StringSplitOptions.RemoveEmptyEntries)
    .Select(s => s.Trim() + "'");
testString = string.Join(Environment.NewLine, split);

【讨论】:

  • 感谢完美运行,速度是我的两倍,甚至无法正常运行。
【解决方案2】:

另一个解决方案有两个简单的String.Replace()

using System;

public class Program
{
    public static void Main()
    {
        string s = "this'is'my'test'\r\nstring'\r\n";
        s = s.Replace(Environment.NewLine, String.Empty); // remove /r/n
        s = s.Replace("'", "'" + Environment.NewLine); // replace ' by ' + /r/n
        Console.WriteLine(s);
    }
}

输出:

this'
is'
my'
test'
string'

【讨论】:

  • @TimSchmelter 我编辑了 sn-p。现在我保留了它。顺便爱你的。比我的更性感,你删除了空格。我投了赞成票。
【解决方案3】:

如果你真的想使用正则表达式(Tim 的解决方案看起来更好)

    string test = "this'is'my'test'\r\nstring'";

    test = Regex.Replace(test,@"[\r\n]","");
    Regex rgx = new Regex("(\\w')([\\\\r]?[\\\\n]?)", RegexOptions.IgnoreCase);
    var rep = rgx.Replace(test,"$0\r\n");

    Console.WriteLine(rep);

结果

this'
is'
my'
test'
string'

//KH

【讨论】:

  • 我同意他看起来更好。此外,这个对我来说也不是完全有效,如果 ' 前面有空格,那么它没有添加换行符。
  • 好吧,我想空格只是一个调整,但如果 Tims 对你有用,我会选择那个,对于未来使用正则表达式的工作,这个站点非常适合测试正则表达式语法 derekslager.com/blog/posts/2007/09/…跨度>
猜你喜欢
  • 2021-03-04
  • 2021-11-22
  • 1970-01-01
  • 2021-07-11
  • 1970-01-01
  • 2014-08-01
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多