-1

I need to write a regular expression that matches all strings containing one or more of the following substrings (including the curly brackets):

{NN}
{NNN}
{NNNN}
{NNNNN}
{NNNNNN}

I am completely new to regular expressions. Can anybody help?

Tintin81
  • 9,821
  • 20
  • 85
  • 178
  • 2
    Possible duplicate of [Learning Regular Expressions](https://stackoverflow.com/questions/4736/learning-regular-expressions) – jonrsharpe May 27 '17 at 07:19

2 Answers2

3
r = /
    \{      # match left brace
    N{2,6}  # match between 2 and 6 Ns
    \}      # match right brace
    /x      # free-spacing regex definition mode

arr = %w|{N} {NN} {NNN} {NNNN} {NNNNN} {NNNNNN} {NNNNNNN} {NNMN}|
  #=> ["{N}", "{NN}", "{NNN}", "{NNNN}", "cat{NNNNN}dog", "{NNNNNN}",
  #    "{NNNNNNN}", "{NNMN}"]

arr.each { |s| puts "'#{s}'.match(r) = #{s.match?(r)}" }
'{N}'.match(r) = false
'{NN}'.match(r) = true
'{NNN}'.match(r) = true
'{NNNN}'.match(r) = true
'cat{NNNNN}dog'.match(r) = true
'{NNNNNN}'.match(r) = true
'{NNNNNNN}'.match(r) = false
'{NNMN}'.match(r) = false
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
1

You didn't specify language / interface you'd be using... In general: \{.*?\} . Replace .*? with N{2,6}? if you want to match only the string you presented.

Ruby example:

if ( content =~ /\{N{2,6}\}/ )
   puts "Content match!"
end
zwer
  • 24,943
  • 3
  • 48
  • 66