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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...