我想匹配这个字符串“$ 0.05/$ 0.10”,并提出了这个正则表达式,但我不断收到错误的换行符表达式,在哪里出错了?很明显,字符串可以改变,可以有或没有小数位,所以这也是有效的$ 25/$ 50或$ 1/$ 2。
我尝试:
@"\(\$(\d+\.\d{2})\+\$(\d+\.\d{2})\));
但很明显,这是行不通的!
我想匹配这个字符串“$ 0.05/$ 0.10”,并提出了这个正则表达式,但我不断收到错误的换行符表达式,在哪里出错了?很明显,字符串可以改变,可以有或没有小数位,所以这也是有效的$ 25/$ 50或$ 1/$ 2。
我尝试:
@"\(\$(\d+\.\d{2})\+\$(\d+\.\d{2})\));
但很明显,这是行不通的!
有些事情错了你的原始表达式:
@"^\$(\d+(?:\.\d{2})?)/\$(\d+(?:\.\d{2})?)$"
短,但完整的例子:
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main()
{
Match("$25/$2.05");
Match("$2.05/$2.05");
Match("$25.00/$22.05");
Match("$25/$10");
Match("x/$10");
Match("$10/x");
Match("$10$20");
}
private static readonly Regex Pattern = new Regex
(@"^\$(\d+(?:\.\d{2})?)/\$(\d+(?:\.\d{2})?)$");
static void Match(string text)
{
Match match = Pattern.Match(text);
if (!match.Success) {
Console.WriteLine("{0}: Match failed", text);
return;
}
Console.WriteLine("{0}: Matched! First: {1} Second: {2}",
text, match.Groups[1], match.Groups[2]);
}
}
输出:您可以将整个图案使用组0
这里是固定的版本总是与
$25/$2.05: Matched! First: 25 Second: 2.05
$2.05/$2.05: Matched! First: 2.05 Second: 2.05
$25.00/$22.05: Matched! First: 25.00 Second: 22.05
$25/$10: Matched! First: 25 Second: 10
x/$10: Match failed
$10/x: Match failed
$10$20: Match failed
@Kobi:是的,正在解决这个问题。 @NullUserException:是的,我也删除了。 – 2010-09-19 07:51:02
Jon,谢谢你,并且感谢我解释错误的地方,“+”很奇怪,因为我实际上复制了错误的正则表达式,这很烦人,但是很晚了,当时我被激怒了。一个问题:我如何修改它,因为我想匹配整个字符串,所以$ 25/$ 2.05是第一个匹配,而不是返回两个匹配?谢谢。 – flavour404 2010-09-19 17:20:04
@ flavour404:只需使用match.Groups [0]。这总是“完全匹配”。 – 2010-09-19 17:36:04
你能更好地描述你想要做什么?你是否试图从文本块中匹配这些文本,或者从完整的输入中解析(在这种情况下,你不需要正则表达式)?那么空间呢? – Kobi 2010-09-19 08:08:02