繁体   English   中英

这个正则表达式是否正确:您将如何改进它?

[英]Is this Regular Expression Correct: How would you improve it

我正在尝试使用C#中的正则表达式编辑字符串。 在阅读下面的预期结果之后; 我的正则表达式是否正确,如果不正确,我怎样才能改进它们?

方法:

  • 对于每个“{”字符:确保它不位于空行(前导和尾随空格和格式字符构成一个空行)
  • 对于每个“}”字符:确保它位于自己的行上而没有其他文本

例如:从此转换:

string super
\v\t { abc

    colour "red" }

对此:

string super { 
abc

    colour "red" 
}

我的代码:

public string[] formatFileContents(string fileContents) {
  Regex openBrkRgx   = new Regex(@"([\c\s]+){");
  // does \c capture whitespace chars?

  fileContents       = openBrkRgx.Replace(fileContents, "{\r\n");

  Regex closedBrkRgx = new Regex(@"[\d\w]}[\d\w]"); 
  // is the above regex comprehensive in your opinion - 
  // ie, can you think of areas where this might fail?

  fileContents       = rgx.Replace(fileContents, "\r\n}\r\n");      
}

你为什么在第二个正则表达式中使用\\d 你替换了数字。 我猜,以下代码更正确:

const string delimeters = @"[\t\r\n\v\b\s]";

var openBrkRgx = new Regex(delimeters + "*{" + delimeters + "?");
fileContents = openBrkRgx.Replace(fileContents, " {\r\n");

var closedBrkRgx = new Regex(delimeters + "*}" + delimeters + "?");
fileContents = closedBrkRgx.Replace(fileContents, "\r\n}\r\n");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM