【问题标题】:search and replace text and numbers in Textfile using .NET c#使用 .NET c# 搜索和替换文本文件中的文本和数字
【发布时间】:2016-09-02 13:34:56
【问题描述】:

我想在物料清单描述中查找并替换毫米到厘米。我必须在 int number 旁边找到单词 mm,然后将单词 mm 更改为 cm 并将数字乘以 0.1 倍,问题是描述可能会有所不同,例如:

  • 半板 ¼ 英寸长 188mm1065mm,不锈钢 316 蕾丝 3/4 cal 16 x 1120 mm ss 304
  • 气垫骑行 3/16 38mm 宽度,972mm 长度 ss316
  • 真空板L.972mm W.288mm ss304

我有以下正则表达式来查找文本,但它不能按预期工作,有时会在 150mm 中找到 0mm:

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");
}

那么..,你有什么想法吗?也许是更复杂的正则表达式或查找和替换库...谢谢!

【问题讨论】:

标签: .net regex search replace find


【解决方案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

【讨论】:

  • 请在投票时留下一些相关的 cmets。
猜你喜欢
  • 2012-08-06
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
  • 2010-12-04
  • 2013-06-13
相关资源
最近更新 更多