2

我有以下输入字符串

some text ) more text
some text , more text
some text ! more text
some text ; more text
some text ? more text
some text . more text
some text)more text
some text,more text
some text!more text
some text;more text
some text?more text
some text.more text
some text )more text
some text ,more text
some text !more text
some text ;more text
some text ?more text
some text .more text

我正在使用 Regex.Replace 方法希望得到

some text) more text
some text, more text
some text! more text
some text; more text
some text? more text
some text. more text
some text) more text
some text, more text
some text! more text
some text; more text
some text? more text
some text. more text
some text) more text
some text, more text
some text! more text
some text; more text
some text? more text
some text. more text

但我的字符串保持不变。

这是我的课:

public class PunctionationSignsSpaceing : ILanguageRuleFormater
    {
        private string _pattern;
        public PunctionationSignsSpaceing()
        {
            _pattern ="( *[),!;?.] *)";
        }
        public string FormatString(string str)
        {
            str = Regex.Replace(
                str,_pattern,"$1",
                RegexOptions.Multiline|RegexOptions.Compiled
            );
            return str;
        }
    }

我在这里做错了吗?(我对正则表达式有点陌生。)谢谢

4

2 回答 2

3

您的正则表达式无效。您正在用自己替换整个匹配项,这就是为什么您在结果字符串中看不到任何变化的原因。

试试那个:

public class PunctionationSignsSpaceing
{
    private string _pattern;
    public PunctionationSignsSpaceing()
    {
        _pattern = " *([),!;?.]) *";
    }
    public string FormatString(string str)
    {
        str = Regex.Replace(
            str, _pattern, "$1 ",
            RegexOptions.Multiline | RegexOptions.Compiled
        );
        return str;
    }
}

您还应该考虑将_pattern初始化从对象构造函数移动到字段本身:

public class PunctionationSignsSpaceing
{
    private string _pattern = " *([),!;?.]) *";

    public string FormatString(string str)
    {
        str = Regex.Replace(
            str, _pattern, "$1 ",
            RegexOptions.Multiline | RegexOptions.Compiled
        );
        return str;
    }
}
于 2013-04-07T14:09:32.720 回答
0

这是一个不使用正则表达式的解决方案

public static void Main (string[] args)
{
    char[] punctiationMarks = new char[]{'.', ',', '?', '!', ';', ')'};
    string inputString = "foo; bar;foo ,  bar , foo\nbar, foo ) bar foo  )bar";
    StringBuilder outputString = new StringBuilder ();
    int indexOfPunctuationMark = -1;
    inputString
        .Split (punctiationMarks, StringSplitOptions.None)
        .ToList ()
            .ForEach (part => {
                indexOfPunctuationMark += part.Length + 1;
                outputString.Append (part.Trim ());
                if (indexOfPunctuationMark < inputString.Length)
                    outputString.Append (inputString [indexOfPunctuationMark]).Append (" ");
            }
    );

    Console.WriteLine (outputString);
}
于 2013-04-07T14:39:33.287 回答