1

I can't find the right Regex code to match this:

  • tttttg must be true
  • tg must be true
  • tgg must be false
  • tttgg must be false
  • t must be true
  • ttt must be true
  • g must be false
  • gggg must be false

There can be any number of occurrences of t but at least one and it can optionally have only a g at the ending. I tried Match match = Regex.Match("ttgg", @"[t]+{g}|[t]+"); but it returns true, it must return false because there are 2 of g and there can only be one.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Bogdan
  • 402
  • 2
  • 8
  • 18

2 Answers2

5

The problem is that given the input string, "ttgg", your pattern will happily match the substring "ttg". Try putting start (^) and end ($) anchors around your pattern to prohibit extra leading or trailing characters. Other than that, you can significantly simply your pattern to this:

Match match = Regex.Match("ttgg", @"^t+g?$")

This will match:

  • the start of the string (^)
  • one or more t characters
  • an optional g character
  • the end of the string
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
1

The regex to use is: "\bt\b|t+g\b|\bt+\b"

\bt\b matches the lone t - word boundary, 't', word boundary. t+g\b matches the remainder - one or more 't' and one and one only g.

I'm presuming your targets don't necessarily start at the beginning of the line.

Phillip Ngan
  • 15,482
  • 8
  • 63
  • 79