正则表达式只修剪句子

时间:2015-06-16 20:58:21

标签: c# regex

我很难弄清楚正则表达式。 我有句子: “1A11 - 车辆发动机控制单元(VECU)(背板) “1A1K5 - 车辆后视图(前视图)” 我想从(----)修剪我的句子,我有这个正则表达式“@”\ s *([^]] *)“但这个问题就像在我的第一句中一样(VECU)是缩写,所以我需要保留它。但是如果我有2()(),这个正则表达式不起作用。如何修改我的正则表达式2仅修剪句子中的last()?

 if (!reportMode)
 {
     //Look line by line for Title                               
     stream = GetStream(files);
     List<String> fileContent = new List<String>();
     using (StreamReader sr = new StreamReader(stream))
     {
        String line = "";
        Boolean isInThere = false;
        while (!sr.EndOfStream)
        {
           line = sr.ReadLine();
           if (line.Contains(title))
           {
              //check for exact match
              Int32 index = line.IndexOf(" - ");
              String revisedLine = line.Substring(index + 3).Trim();
              String str = Regex.Replace(revisedLine, @"\s*\([^\)]*\)", "").Trim();
              if (Regex.IsMatch(str, String.Format("^{0}$", title)))
                  isInThere = true;
           }
           fileContent.Add(line);
      }

2 个答案:

答案 0 :(得分:1)

您可以将正则表达式锚定在该行的末尾。通常在末尾添加一个'$'符号:“\ s * \([^ \]] * \)$”。如果右括号是字符串的最后一个字符,则应该这样做。否则,您可以添加表达式以忽略空格。

(修正了regexp语法,谢谢Patrick)

- MAXP

答案 1 :(得分:1)

如果您需要删除最后但不仅仅在最后出现的括号表达式,您可以使用

Regex rx = new Regex(@"\s*\([^()]*\)(?=[^()]*$)");
String str = rx.Replace(revisedLine, "").Trim();

REGEX:

  • \s* - 0个或更多空格符号
  • \([^()]*\) - 圆括号后跟除)(
  • 以外的任意数量的字符
  • (?=[^()]*$) - 在字符串结尾之前检查是否没有()符号的前瞻。

请注意,您不需要转义字符类中的圆括号。