简体   繁体   中英

How to check Equal Sign in string using REGEX in C#

I want to check string which look like following

1st radius = 120

and

2nd radius = 'value'

Here is my code

v1 = new Regex(@"^[A-Za-z]+\s[=]\s[A-Za-z]+$");
if (v1.IsMatch(singleLine))`
{
    ...
    ...
}

Using @"^[A-Za-z]+\s[=]\s[A-Za-z]+$" this expression 2nd string is matched but not first and when used this @"^[A-Za-z]+\s[=]\s\d{0,3}$" then only matched first one.

And i also want to check for radius = 'val01'

Basing on your effort, it looks as if you were trying to come up with

^[A-Za-z]+\s=\s(?:'[A-Za-z0-9]+'|\d{1,3})$

See the regex demo . Details :

  • ^ - start of string
  • [A-Za-z]+ - one or more ASCII letters
  • \s=\s - a = char enclosed with single whitespace chars
  • (?:'[A-Za-z0-9]+'|\d{1,3}) - a non-capturing group matching either
    • '[A-Za-z0-9]+' - ' , then one or more ASCII letters or digits and then a '
    • | - or
    • \d{1,3} - one, two or three digits
  • $ - end of string (actually, \z is safer when it comes to validating as there can be no final trailing newline after \z , and there can be such a newline after $ , but it also depends on how you obtain the input).

If the pattern you tried ^[A-Za-z]+\s[=]\s[A-Za-z]+$ matches the second string radius = 'value' , that means that 'value' consists of only chars A-Za-z.

In that case, you could either add matching digits to the second character class:

^[A-Za-z]+\s=\s[A-Za-z0-9]+$

If you either want to match 1-3 digits or at least a single char A-Za-z followed by optional digits:

^[A-Za-z]+\s=\s(?:[0-9]{1,3}|[A-Za-z]+[0-9]*)$

The pattern matches:

  • ^ Start of string
  • [A-Za-z]+\s=\s Match the first part with chars A-Za-z and the = sign ( Note that = does not have to be between square brackets)
  • (?: Non capture group
    • [0-9]{1,3} Match 1-3 digits (You can use \d{0,3} but that will also match an emtpy string due to the 0 )
    • | Or
    • [A-Za-z]+[0-9]* Match 1+ chars A-Za-z followed by optional digits
  • ) Close non capture group
  • $ End of string

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