0

我在重写字符串中两个“关键字”之间的字符串时遇到了一些问题。这是有问题的正则表达式模式:

modify = Regex.Replace(modify, "FEW([0-9]{3})", "few clouds at $1.");
modify = Regex.Replace(modify, @"(?s)(?<=[0-9]{2}SM).+0([0-9]{1})0.+?(?=[0-9]{2}/[0-9]{2})", "$2 thousand");

基本上我需要在 METAR 中获取云层,特别是“FEW070”

KLAX 032109Z 26014KT 10SM FEW070 SCT120 BKN220 21/17 A2986 RMK AO2

我希望它在 7000 点返回几朵云,但它在 070 点返回几朵云。

我一直在使用这个程序来测试正则表达式并使用上面的模式,它返回 7 就像它应该的那样。

4

2 回答 2

1

尝试这个:

modify = Regex.Replace(modify, @"FEW0*(\d+)0", "few clouds at $1,000.");
于 2013-07-03T22:28:44.133 回答
0

一个更简单的正则表达式可能会更好,但这是你的问题:

  • 也不(?s)(?<=...)捕获组,因此您必须使用$1而不是$2获取7.
  • 您将字符串替换为"few clouds at 070",但随后您不再记得该"few clouds at "部分。您应该放在.+括号中并使用$1$2而不是$1.
  • 您可能应该使用.+?而不是.+.

最终代码:

modify = Regex.Replace(modify, "FEW([0-9]{3})", "few clouds at $1");
modify = Regex.Replace(modify, @"(?s)(?<=[0-9]{2}SM)(.+?)0([0-9]{1})0.+?(?=[0-9]{2}/[0-9]{2})", "$1$2 thousand.");

测试

于 2013-07-03T23:03:17.757 回答