2016-02-15 44 views
0

我創建了一個正則表達式,它刪除特殊字符,如(<>'&),並在兩個單詞之間創建每個單詞大寫的首字母和下劃線(_)。例如,
輸入:"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); 
    } 
} 

感謝

+4

可能重複的[正則表達式去除撇號](http://stackoverflow.com/questions/1219915/regex-to-remove-apostrophe) – MethodMan

+0

請檢查是否[這是按預期工作](http:// ideone的.com/AFaeEy)。 –

+0

@WiktorStribiżew非常感謝您的快速回復。 – VSharma

回答

0

您可以採用如下方案:

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}))並捕獲該信件,以便稍後我們可以檢查該組是否參與了比賽(如果是,請將其轉成大寫),或者僅匹配'以將其替換爲無。