2017-05-27 263 views
-1

我需要编写一个包含以下子的一个或多个(包括大括号)所有字符串匹配的正则表达式信:正则表达式匹配括号内

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

我完全新的正则表达式。任何人都可以帮忙吗?

+2

的可能的复制[学习正则表达式(https://stackoverflow.com/questions/4736/learning-regular-expressions) – jonrsharpe

回答

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 
+0

正则表达式像一个魅力,非常感谢。 – Tintin81

1

你没有指定你正在使用的语言/界面......一般来说:\{.*?\}。如果您只想匹配您呈现的字符串,请将.*?替换为N{2,6}?

红宝石例如:

if (content =~ /\{N{2,6}\}/) 
    puts "Content match!" 
end 
+0

我使用Ruby on Rails 。 – Tintin81