Bogdan
Bogdan

Reputation: 412

Regex for a string of repeating characters and another optional one at the end

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

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.

Upvotes: 1

Views: 14583

Answers (2)

Phillip Ngan
Phillip Ngan

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

p.s.w.g
p.s.w.g

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:

  • the start of the string (^)
  • one or more t characters
  • an optional g character
  • the end of the string

Upvotes: 5

Related Questions