如何解决Rails-从字符串中提取带有[和]的子字符串
这有效。
"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"
但是我想提取[
和]
中的子字符串。
输入:
string = "123 [asd]"
输出:
asd
有人可以帮助我吗?
解决方法
您可以这样做:
"123 [asd]"[/\[(.*?)\]/,1]
将返回
"asd"
您可以在这里进行测试: https://rextester.com/YGZEA91495
,还有其他几种提取所需字符串的方法。
str = "123 [asd] 456"
#1
r = /
(?<=\[) # match '[' in a positive lookbehind
[^\]]* # match 1+ characters other than ']'
(?=\]) # match ']' in a positive lookahead
/x # free-spacing regex definition mode
str[r]
#=> "asd"
#2
r = /
\[ # match '['
[^\]]* # match 1+ characters other than ']'
\] # match ']'
/x # free-spacing regex definition mode
str[r][1..-2]
#=> "asd"
#3
r = /
.*\[ # match 0+ characters other than a newline,then '['
| # or
\].* # match ']' then 0+ characters other than a newline
/x # free-spacing regex definition mode
str.gsub(r,'')
#=> "asd"
#4
n = str.index('[')
#=> 4
m = str.index(']',n+1)
#=> 8
str[n+1..m-1]
#=> "asd"
请参见String#index。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。