为什么正则表达式中的组无法正常工作 [英] Why are groups in regex doesn't works correctly
问题描述
Match match = Regex.Match(textBox1.Text, @"(\d)*(\d)");
MessageBox.Show(match.Groups[1].Value.ToString());
double x2 = Convert.ToDouble(match.Groups[1].Value.ToString());
double x1 = Convert.ToInt32(match.Groups[2].Value.ToString());
textBox1.Text = Regex.Replace(textBox1.Text, @"\d*\d", (x1 * x2).ToString());
我的尝试:
我一直在尝试编写数学解析器,我遇到了正则表达式组的问题,例如
textBox.Text = 2 * 2 >
和match.Groups [1] .Value为空。
What I have tried:
I have been trying to write a math parser and I catch a problem with regex groups for example
textBox.Text = 2*2
and match.Groups[1].Value is empty.
推荐答案
为什么正则表达式中的组无法正常工作
Why are groups in regex doesn't works correctly
因为*在RegEx中有特殊含义,当你想要使用时它是文字的。你需要逃避*到\ *。
只是一些有趣的链接来帮助构建和调试RegEx。
这是一个链接到RegEx文档:
perlre - perldoc.perl.org [ ^ ]
以下是帮助构建RegEx和调试的工具的链接他们:
.NET Regex Tester - Regex Storm [ ^ ]
Expresso正则表达式工具 [ ^ ]
RegExr:Learn,Build,&测试RegEx [ ^ ]
在线正则表达式测试器和调试器:PHP,PCRE,Python,Golang和JavaScript [ ^ ]
这个显示RegEx是一个很好的图表,它非常有助于理解RegEx的作用: Debuggex:在线可视正则表达式测试器。 JavaScript,Python和PCRE。 [ ^ ]
此网站还在一个漂亮的图表中显示正则表达式,但无法测试与RegEx匹配的内容: Regexper [ ^ ]
Because * have a special meaning in RegEx, when you want to use it as literal. You need to escape * to \* .
Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx: Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx: Regexper[^]
为了更好地理解
For your better understanding
using System;
using System.Text.RegularExpressions;
namespace myApp
{
class Program
{
static void Main(string[] args)
{
String chk = "5*6";
Match match = Regex.Match(chk, @"(\d)\*(\d)");
Console.WriteLine(match.Groups[0]);
Console.WriteLine(match.Groups[1]);
Console.WriteLine(match.Groups[2]);
}
}
}
结果:
Result:
myApp
dotnet run
5 * 6
5
6
dotnet run 5*6 5 6
这篇关于为什么正则表达式中的组无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!