简体   繁体   中英

c# regex - match either a word or a number (int or float)

I'm currently programming a resolver for math expressions and have the following situation: A user can either define a formula with parameters (a word) or numbers. Therefor I need to resolve a given string to either a word or a number that can be integer or float and I want to save the result eg as "left hand side" (lhs): Unfortunately I have problems with the regex:

I tried something like:

Match m1 = Regex.Match("variable", @"^(?<lhs>((\w+)|(([0-9]+)(\.([0-9]*))?)))");
Match m2 = Regex.Match("1.2", @"^(?<lhs>((\w+)|(([0-9]+)(\.([0-9]*))?)))");

Expected result would be that I get a group "lhs" that contains the string "variable" for m1 or "1.2" for m2. Actual result is that I get the whole word "variable" in m1, but in case of the number in m2, just the first digit "1" is matched. If I exlude the possibility for word "1.2" is found:

Match m3 = Regex.Match("1.2", @"^(?<lhs>(([0-9]+)(\.([0-9]*))?))");

Can anyone help me here?

The \\w+ pattern matches letters, digits , and some other chars, including _ . Since it is the first part in the alternation group, once it matches a digit, it is never retried with the second alternative.

You may swap the branches, and use something like

^(?<lhs>(?<num>[0-9]+(?:\.[0-9]*)?)|(?<word>\w+))

Or, if the whole string should match:

^(?<lhs>(?<num>[0-9]+(?:\.[0-9]*)?)|(?<word>\w+))$

See the .NET regex demo .

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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