2016-05-07 89 views
0

我想查找並替換材料清單中的毫米至釐米的描述。我要找到下一個爲int號碼,然後改變字毫米到釐米和乘數的0.1倍的話毫米,問題是,描述可以例如改變:使用.NET c搜索並替換文本文件中的文本和數字#

  • 半板¼英寸長度188毫米高度1065毫米,SS 316 花邊3/4 CAL 16×1120毫米 SS 304
  • 空氣coushion騎着3/16 38毫米寬度,972毫米長度SS316
  • VACUU m的合金板L.972mmW.288mm SS304

我有以下的正則表達式查找的文字,但預期它不工作,有時發現0毫米150毫米:

string txt = textBox1.Text; 
string re1 = ".*?"; // Non-greedy match on filler 
string re2 = "\\d+"; // Uninteresting: int 
string re3 = ".*?"; // Non-greedy match on filler 
string re4 = "\\d+"; // Uninteresting: int 
string re5 = ".*?"; // Non-greedy match on filler 
string re6 = "\\d+"; // Uninteresting: int 
string re7 = ".*?"; // Non-greedy match on filler 
string re8 = "(\\d+)"; // Integer Number 1 
string re9 = ".*?"; // Non-greedy match on filler 
string re10 = "(mm)"; // Word 1 

// ".*?\\d+.*?\\d+.*?\\d+.*?(\\d+).*?(mm)" 

Regex r = new Regex(re1 + re2 + re3 + re4 + re5 + re6 + re7 + re8 + re9 + re10, 
    RegexOptions.IgnoreCase | RegexOptions.Singleline); 
Match m = r.Match(txt); 
if (m.Success) 
{ 
    String int1 = m.Groups[1].ToString(); 
    String word1 = m.Groups[2].ToString(); 
    MessageBox.Show("(" + int1.ToString() + ")" 
     + "(" + word1.ToString() + ")" + "\n"); 
} 

所以..,你有什麼想法嗎?也許一個更復雜的正則表達式或一個庫查找和替換...謝謝!

+0

[這裏是一個可能的解決方案](http://pastebin.com/raw/5kF597eY)它可以被開發爲將值乘以0.1 – Deano

+1

你不能將這些數字與['@「(\ d +)\ s * mm \ b」'](https://regex101.com/r/zS1kJ1)/1),然後使用匹配評估程序更改爲cm? –

回答

1

這裏是Ideone一個工作程序:

string s = @"Half plate ¼ inch length 188mm height 1065mm, ss 316 Lace 3/4 cal 16 x 1120 mm ss 304 
      Air coushion rode 3/16 38mm width, 972mm length ss316 
      Vacuum plate L.972mm W.288mm ss304"; 

Regex regex = new Regex(@"(\d+)(\s*)(mm)"); 

string ns = regex.Replace(s, delegate (Match m) { 
    return Int32.Parse(m.Groups[1].Value) * 0.1 + m.Groups[2].Value + "cm"; 
}); 

Console.WriteLine(ns); 

並且輸出是:

Half plate ¼ inch length 18.8cm height 106.5cm, ss 316 Lace 3/4 cal 16 x 112 cm ss 304 
Air coushion rode 3/16 3.8cm width, 97.2cm length ss316 
Vacuum plate L.97.2cm W.28.8cm ss304 
+1

請留下一些相關的評論以及downvoting。 – AKS

相關問題