在字符串的两边替换字符?

时间:2017-11-11 13:26:08

标签: c# regex

好的,我只是想直接拿出来,我不知道怎么做,我尽可能多地尝试但没有成功。

要使左边的字符串看起来像ReGex右边的结果,字符串看起来像这样,

  

String---String == String-String

当中间字符与周围的两个字符不同时会发生这种情况,

  

String=@=string-String == String@string-String

编辑,这也是一种可能性,

  

String@@@String == String@String

非常感谢任何向正确方向的推动。

4 个答案:

答案 0 :(得分:0)

不替换方法工作吗?选择和替换可能更容易。 顺便使用正则表达式,您可以尝试以下代码:

        string text = "String-MyString-String";
        var pattern = "\\-";
        var match = Regex.Replace(text, pattern, "");

编辑:所以你需要删除字符串上的第一个和最后一个减号字符,或者你需要替换它?如果您需要删除它,您可以尝试这部分代码:

        text = text.Remove(text.IndexOf('-'), 1);
        text = text.Remove(text.LastIndexOf('-'), 1);

如果需要替换char,可以使用stringBuilder替换所选位置的值。

答案 1 :(得分:0)

嗯,我能在几天之后弄清楚这一点。

这里的问题是Regex它会匹配一个字符串作为一个整体,所以如果我想从匹配中排除一个字符,我可以通过使用Regex删除匹配字符串中的第一个或最后一个字符来实现。但不幸的是,你不能在匹配的结果中捕获一个字符。

所以,当我想要匹配另一个角色的角色时,如下所示;

enter image description here

因此,根据我对RegEx的理解,这是不可能的。

但是,我能够使用look-around匹配每一个字符,但是b / c它不是单个匹配,它只有匹配单个字符的不良结果以及如下;

代码是,

var match = Regex.IsMatch(text, @"(?<=[a-zA-Z0-9])[=@\-_]|[=@\-_](?=[a-zA-Z0-9])");

结果如下,这也只是单个字符的匹配,这是不可取的。

enter image description here

所以改变了对方法的思考(我不知道为什么我一开始没有这样做,除了我如此专注于匹配所需角色的任何一方的角色,我可以没有看到森林的树木)。当两个相同的字符出现在Word CharactersDigits之前时,方法是匹配,所以我再次使用look-around并想出了这个; 这是代码,

var match =  Regex.IsMatch(subjectString, @"[=@\-_]{2}(?=[a-zA-Z0-9])");

将结果看起来像这样,

enter image description here

现在正是我想要的。但是,这并没有解决问题,因为当中间的字符或字符串与任何一方的字符不同时,上面的字符将会失败。

所以我提出了这个问题,并在我的案例中回答了我的问题。它不是完全匹配,但匹配两个不同的条件以获得我需要的结果。

var match =  Regex.IsMatch(subjectString, @"(?<=[a-zA-Z0-9])[@\-=_](?=[@\-=_])|(?<=[@\-=_])[@\-=_](?=[a-zA-Z0-9])");

结果就是这样;

enter image description here

我并不关心人们对这个问题的看法,但希望这个答案可以帮助某人尝试在characterstring character的任意一方进行一场比赛}

答案 2 :(得分:-1)

Oh, I know why you unable to do this. Of course, if you write regex pattern like this:

-

it won't work, for it to work you need to escape it:

\-

so it works like this:

var result = Regex.Replace(str, @"\-","");

so, yeah this pattern will work. But as Jon Skeet said you can just replace it through much simplier way:

var result = str.Replace("-", "");

答案 3 :(得分:-1)

不使用正则表达式:

static string RemoveChars(string input, params char[] chars)
{
  string output = string.Empty;

  for (int i = 0; i < input.Length; i++)
    if (!chars.Contains(input[i]))
      output += input[i];

  return output;
}

测试方法:

string temp1 = "String-MyString-String";
string temp2 = "StringxMyStringyString";
string temp3 = "-x-y-";

Console.WriteLine("Input string: " + temp1 + ", output string: " + RemoveChars(temp1, '-'));
Console.WriteLine("Input string: " + temp2 + ", output string: " + RemoveChars(temp2, 'x', 'y'));
Console.WriteLine("Input string: " + temp3 + ", output string: " + RemoveChars(temp3, 'x', 'y'));

结果:

results