一次更换(倒置)开启和关闭支架

时间:2015-04-21 11:14:25

标签: c# regex

解决方案应该很简单,但仍然在努力。如何反转分组符号,如括号,括号,大括号......

我的字符串就像:Lorem ipsum dolor )sit amet(, consectetur ]adipiscing[ elit

我希望输出为Lorem ipsum dolor (sit amet), consectetur [adipiscing] elit

关键是如果我在多次传递中逐个符号地变换符号,它会被转换两次:

text = text.Replace('[', ']');
text = text.Replace(']', '[');
text = text.Replace('(', ')');
text = text.Replace(')', '(');

结果是Lorem ipsum dolor (sit amet(, consectetur [adipiscing[ elit

如何一次性转换文本?

7 个答案:

答案 0 :(得分:9)

按照古人所做的那样......你按字符重建字符串......

string str = "Lorem ipsum dolor )sit amet(, consectetur ]adipiscing[ elit";

var sb = new StringBuilder(str.Length);

foreach (char ch in str)
{
    switch (ch)
    {
        case '[':
            sb.Append(']');
            break;
        case ']':
            sb.Append('[');
            break;
        case '(':
            sb.Append(')');
            break;
        case ')':
            sb.Append('(');
            break;
        default:
            sb.Append(ch);
            break;
    }
}

string str2 = sb.ToString();

或者您可以开始使用混淆的C#: - )

string str3 = new Regex(@"[\[\]()]")
    .Replace(str, x => ((char)(x.Value[0] + (x.Value == "[" || x.Value == "(" ? 
        1 + (x.Value[0] / '[') : 
        -1 - (x.Value[0] / '[')))).ToString());

答案 1 :(得分:2)

我会使用StringBuilder方法:

static readonly Dictionary<char, char> ReplacementChars = new Dictionary<char, char> 
{ 
       { '[', ']'},{']', '['},{')', '('}, {'(', ')'} 
};

public static string SwapGroupingSymbols(string str)
{
    StringBuilder sb = new StringBuilder(str.Length);
    foreach (char c in str)
    {
        char newChar;
        bool contains = ReplacementChars.TryGetValue(c, out newChar);
        sb.Append(contains ? newChar : c);
    }
    return sb.ToString();
}

测试:

string newStr = SwapGroupingSymbols("Lorem ipsum dolor )sit amet(, consectetur ]adipiscing[ elit");
// Lorem ipsum dolor (sit amet), consectetur [adipiscing] elit

答案 2 :(得分:1)

我还要添加一个正则表达式选项:

string s = "Lorem ipsum dolor )sit amet(, consectetur ]adipiscing[ elit";
s = Regex.Replace(s, @"(\[)|(\])|(\()|(\))", new MatchEvaluator(InvertBrackets));

    private string InvertBrackets(Match m) 
    {
        switch(m.Value) {
            case "(":
                return ")";
            case ")":
                return "(";
            case "[":
                return "]";
            default:
                return "[";
        }  
    }

答案 3 :(得分:0)

字符串是可以使用LINQ处理的序列:

text = new string(text.Select(c =>
 c == '[' ? ']' :
 c == ']' ? '[' :
 ...
 c).ToArray());

这会很慢。处理每个char的手动循环会快得多。

答案 4 :(得分:0)

这是仅使用String.Replace()的最早的解决方法:

var st = "Lorem ipsum dolor )sit amet(, consectetur ]adipiscing[ elit";
st = st.Replace("[", "@@osbr@@").Replace("]", "@@csbr@@").Replace(")", "@@crbr@@").Replace("(", "@@orbr@@");
st = st.Replace("@@osbr@@", "]").Replace("@@csbr@@", "[").Replace("@@crbr@@", "(").Replace("@@orbr@@", ")");

输出:

enter image description here

答案 5 :(得分:0)

我会在两遍中使用正则表达式来表示不同的括号。

string newStr = "Lorem ipsum dolor )sit amet(, consectetur ]adipiscing[ elit";
var newx = Regex.Replace(newStr, "(\\))(.*)(\\()", "($2)");
var newy = Regex.Replace(newx, "(\\])(.*)(\\[)", "[$2]");
newy.Dump();

这会产生。在Linqpad上测试过。

  

Lorem ipsum dolor(sit amet),consectetur [adipiscing] elit

答案 6 :(得分:0)

const string input = @"Lorem ipsum dolor )sit amet(, consectetur ]adipiscing[ elit";

Dictionary<char, char> dic = new Dictionary<char, char> { { '[', ']' }, { ']', '[' }, { '(', ')' }, { ')', '(' } };

string output = new String(input.Select(n => dic.ContainsKey(n) ? dic[n] : n).ToArray());