【问题标题】:Regex to remove special character正则表达式删除特殊字符
【发布时间】:2016-05-26 15:36:36
【问题描述】:

我创建了一个正则表达式,它删除了像 ('&) 这样的特殊字符,并使每个单词的首字母大写,并在两个单词之间填充下划线 (_)。例如,
输入:"V_DV3501_Value can't be empty"
输出:"V_DV3501_Value_Cant_Be_Empty"

我创建的正则表达式产生的输出为,

输出:"V_DV3501_Value_Can't_Be_Empty"

问题是撇号(')字符不会从字符串中替换。如果你能在解决这个问题的代码中提出任何其他模式,我可以。

class Program
{
    static void Main(string[] args)
    {
        string createString = "";
        string input = "";

        var pattern = @"(?:[^a-zA-Z_]*)((?<output>[a-zA-Z0-9_]*)[\s+&<>\',\/=-]*|$)*";

        var subject = "V_DV3501_Value can't be empty";

        subject = subject.ToString().Replace("&", "and");

        var regex = new Regex(pattern);

        var match = regex.Match(subject);
        Console.WriteLine("pattern: {0} {1} Length: {2}", pattern, match.Success, match.Length);

        foreach (Capture capture in match.Groups["output"].Captures)
        {
            Console.WriteLine("    {0} @ {1} length {2}", capture.Value, capture.Index, capture.Length);

            input = capture.Value + "_";

            if (!String.IsNullOrEmpty(input))
            {
                input = input.First().ToString().ToUpper() + input.Substring(1);
            }

            createString = createString + input;

        }

        createString = createString.Remove(createString.Length - 2);
        Console.WriteLine("Final: " + createString);
    }
}

谢谢

【问题讨论】:

标签: c# regex


【解决方案1】:

您可以使用以下解决方案:

var str = "V_DV3501_Value can't be empty";
var res = Regex.Replace(str, @"[\W-[']](\p{L})|'", m =>
      m.Groups[1].Success ? string.Format("_{0}", m.Groups[1].Value.ToUpper()) : "");
Console.WriteLine(res);
// => V_DV3501_Value_Cant_Be_Empty

IDEONE demo

这里的想法是使用[\W-[']](\p{L})|' 正则表达式匹配除' 之外的任何非单词字符(使用[\W-[']],稍后替换为_)后跟一个字母(使用(\p{L}) ) 并捕获该字母,以便稍后我们可以检查该组是否参加了比赛(如果是,则将其转为大写),或者仅匹配 ' 以将其替换为空。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    相关资源
    最近更新 更多