我有一个这样的字符串:
Hi my name is John (aka Johnator)
.
获取括号(包括括号)之间的内容的最佳方法是什么?
您可以将String#[]与正则表达式一起使用:
a = "Hi my name is John (aka Johnator)"
a[/\(.*?\)/]
# => "(aka Johnator)"
用于[^()]*?
选择括号中的文本:
a = "Hi (a(b)c) ((d)"
# => "Hi (a(b)c) ((d)"
a.gsub(/\([^()]*?\)/) { |x| p x[1..-2]; "w"}
"b"
"d"
# => "Hi (awc) (w"
试试这个:
str1 = ""
text = "Hi my name is John (aka Johnator)"
text.sub(/(\(.*?\))/) { str1 = $1 }
puts str1
编辑:没有读到离开括号!