Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
C#
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());


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.
Posted
Updated 27-May-19 12:17pm
v2
Comments
Dave Kreskowiak 27-May-19 17:33pm    
Whether this works or not depends on the complexity of the expressions you're planning on supporting. If it's nothing more than "some value * some value", then you could get away with a set of RegEx's to grab the numbers and do the math.

If you're planning on something more complex, RegEx's are not going to it for you.

Quote:
Why are groups in regex doesn't works correctly

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[^]
 
Share this answer
 
For your better understanding
C#
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
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900