Reputation: 412
I can't find the right Regex
code to match this:
tttttg
must be truetg
must be truetgg
must be falsetttgg
must be falset
must be truettt
must be trueg
must be falsegggg
must be falseThere 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.
Upvotes: 1
Views: 14583
Reputation: 16106
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.
Upvotes: 1
Reputation: 149020
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:
^
)t
charactersg
characterUpvotes: 5