2012-06-07 18 views
1

我想剝離字符串,但只留下了以下內容:正則表達式除去給定的字符?

[a-zA-Z]+[_a-zA-Z0-9-]* 

我試圖與一個字符開始輸出字符串,然後可以有字母,下劃線和破折號。我如何使用RegEx或其他功能來做到這一點?

+0

你有正則表達式 - 你到底有什麼問題? –

+0

通過字符串你的意思是一個'字符串[]'?是不是「把所有的比賽」都變成了「沒有得到不匹配的東西」? – vcsjones

回答

2

因爲一切都在正則表達式的第二部分是在第一部分中,你可以做這樣的事情:

String foo = "[email protected]#$5o993idl;)"; // your string here. 
//First replace removes all the characters you don't want. 
foo = Regex.Replace(foo, "[^_a-zA-Z0-9-]", ""); 
//Second replace removes any characters from the start that aren't allowed there. 
foo = Regex.Replace(foo, "^[^a-zA-Z]+", ""); 

因此,通過配對開始了它只有允許的字符。然後擺脫任何不允許的字符。

當然,如果你的正則表達式變得更復雜,這個解決方案很快就會崩潰。

0

編輯

var s = Regex.Matches(input_string, "[a-z]+(_*-*[a-z0-9]*)*", RegexOptions.IgnoreCase); 
      string output_string=""; 
      foreach (Match m in s) 
      { 
       output_string = output_string + m; 

      } 
    MessageBox.Show(output_string); 
+0

這很奇怪..輸入這個sdgfsd * ^%&$ AFSds返回sdgfsd。這就像它找到一個特殊的字符串後退出。 – TruMan1

+0

@ TruMan1你是什麼意思帶? OP詢問關於從給定字符串中剝離字符串。 –

+0

我期望sdgfsd * ^%&$ AFSds返回sdgfsdAFSds,但它返回sdgfsd。 – TruMan1

0

假設你已經有了一個集合中的字符串,我會做這樣說:在收集

  1. 的foreach元素嘗試匹配正則表達式
  2. 如果成功,從去除串! collection

或者相反 - 如果匹配,則將其添加到新集合中。

如果字符串不在集合中,可以添加更多關於輸入內容的細節信息?

0

如果你想拔出所有匹配的正則表達式的標識符,你可以做這樣的:

var input = " _wontmatch f_oobar0 another_valid "; 
var re = new Regex(@"\b[a-zA-Z][_a-zA-Z0-9-]*\b"); 
foreach(Match match in re.Matches(input)) 
    Console.WriteLine(match.Value); 
0

使用MatchCollection matchColl = Regex.Matches("input string","your regex");

然後使用:

string [] outStrings = new string[matchColl.Count]; //A string array to contain all required strings 

for (int i=0; i < matchColl.Count; i++) 
    outStrings[i] = matchColl[i].ToString(); 

你將在outStrings中包含所有必需的字符串。希望這可以幫助。

相關問題