0

In a given program, a string should start and finish with a percentage sign and can contain any number of characters in-between. Therefore, the following strings should be valid:

  • "%%"
  • "% %"
  • "%a%"
  • "%1%"
  • "% a1a %"
  • "%%%"

The following strings (for example) would therefore be invalid:

  • " %%"
  • "%% "
  • " % "
  • " a%%b "

I am trying to validate these using regular expressions but cannot figure the correct expression. In C# I currently have:

Regex.IsMatch(stringToValidate, "%.*%")

All strings provided above currently match. But I do not want it to match the set of invalid strings.

Dangerous
  • 4,818
  • 3
  • 33
  • 48

3 Answers3

1

Use ^%.*%$ with the multi line flag:

https://regex101.com/r/QDX5h3/1

Feodoran
  • 1,752
  • 1
  • 14
  • 31
1

You need to specify an "anchor" (in your case two: start "^" and end "$" of string). Otherwise your pattern will match anywhere inside the complete string and thus " %...% " or abc%...%xx would also match.

Thus, use:

 "^%.*%$"
Christian.K
  • 47,778
  • 10
  • 99
  • 143
1

You can use:

bool foundMatch = Regex.IsMatch(stringToValidate, "^%.*%$");

enter image description here

Regex Demo

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268