2016-10-05 123 views
4

我需要插入一个特定符号之前和之后(单)空格(如“|”),像这样:插入(单)空格前的特定符号,之后

string input = "|ABC|xyz |123||999| aaa| |BBB"; 
string output = "| ABC | xyz | 123 | | 999 | aaa | | BBB"; 

这可以很容易地实现使用一些正则表达式模式:

string input = "|ABC|xyz |123||999| aaa| |BBB"; 

// add space before | 
string pattern = "[a-zA-Z0-9\\s*]*\\|"; 
string replacement = "$0 "; 
string output = Regex.Replace(input, pattern, replacement); 

// add space after | 
pattern = "\\|[a-zA-Z0-9\\s*]*"; 
replacement = " $0"; 
output = Regex.Replace(output, pattern, replacement); 

// trim redundant spaces 
pattern = "\\s+"; 
replacement = " "; 
output = Regex.Replace(output, pattern, replacement).Trim(); 

Console.WriteLine("Original String: \"{0}\"", input); 
Console.WriteLine("Replacement String: \"{0}\"", output); 

但这不是我想要的,我的目标只是使用单一模式。

我尝试了很多方法,但仍然无法按预期工作。请有人帮我解决这个问题。

非常感谢你提前!

+0

定义“不按预期工作”。你没有得到任何回报?错误的结果?一个错误? – Tim

+0

没有错误,但错误的输出结果,例如有更多的空间比必要的(而不是1空间),这就是为什么我想要组合一些模式,但是有可能使用一个模式来实现这一点? –

回答

1

试试这个。

string input = "|ABC|xyz |123||999| aaa| |BBB"; 

string pattern = @"[\s]*[|][\s]*"; 
string replacement = " | "; 
string output = Regex.Replace(input, pattern, replacement); 
+0

谢谢,但''|'''之间仍有多余的空格,输出是'“| ABC | xyz | 123 | | 999 | aaa | | BBB”'。如果没有解决方案,也许我必须使用一种模式来消除多余的空白。 –

+0

@PhongHo我认为你可以使用他的正则表达式来获得你的结果。我们只是写更多的正则表达式C#代码:)。 –

0

尝试这种解决方案的基础上,this answer

var str = "|ABC|xyz |123||999| aaa| |BBB"; 
var fixed = Regex.Replace(str, patt, m => 
      { 
       if(string.IsNullOrWhiteSpace(m.Value))//multple spaces 
        return ""; 
       return " | "; 
      }); 

这将返回| ABC | xyz | 123 | | 999 | aaa | | BBB

我们都还是老样子由于与|更换|BBB|(space)(space)|之间aaa但这是。

4

谢谢@Santhosh Nayak。

我只是写更多的C#代码来获得输出作为OP想要的。

string input = "|ABC|xyz |123||999| aaa| |BBB"; 
string pattern = @"[\s]*[|][\s]*"; 
string replacement = " | "; 
string output = Regex.Replace(input, pattern, (match) => { 
    if(match.Index != 0) 
     return replacement; 
    else 
     return value; 
}); 

我在MSDN中提到Regex.Replace(string input, string pattern, MatchEvaluator evaluator)

相关问题