Ruby on rails 从两个符号之间的字符串中获取元素
我有这样的字符串:Ruby on rails 从两个符号之间的字符串中获取元素,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有这样的字符串: 地址22-99,世界 我需要从这个字符串中获取值99,它位于-和,符号之间。这可能吗?地址22-99,世界[/(?地址22-99,世界[/(?尝试使用gsub: "Adress 22 - 99, world"[/(?<=-[\s*])(.*)(?=,)/] # 99 str = "Jura Alunana 11 - 126, Riga" value = str.gsub(/.*- (\d+),.*/, '\1') # \1 means the digits insid
地址22-99,世界
我需要从这个字符串中获取值99
,它位于-
和,
符号之间。这可能吗?地址22-99,世界[/(?地址22-99,世界[/(?尝试使用gsub:
"Adress 22 - 99, world"[/(?<=-[\s*])(.*)(?=,)/]
# 99
str = "Jura Alunana 11 - 126, Riga"
value = str.gsub(/.*- (\d+),.*/, '\1') # \1 means the digits inside the first ( ) pair
# => "126"
尝试使用gsub:
str = "Jura Alunana 11 - 126, Riga"
value = str.gsub(/.*- (\d+),.*/, '\1') # \1 means the digits inside the first ( ) pair
# => "126"
这是我的观点。我发现它比其他一些解决方案更容易阅读
str = "Jura Alunana 11 - 126, Riga"
str.match(/-\s(\d+),/)
puts $1
# => 126
这是我的观点。我发现它比其他一些解决方案更容易阅读
str = "Jura Alunana 11 - 126, Riga"
str.match(/-\s(\d+),/)
puts $1
# => 126
通过以自由间距模式定义正则表达式,我们可以使其自文档化:
r = /
.* # match 0+ characters
-\D* # match a hyphen followed by 0+ non-digits
\K # forget everything matched so far
\d+ # match 1+ digits...
(?=.*,) # ...followed by 0+ characters then a comma (positive lookahead)
/x # free-spacing regex definition mode
或者
r = /
.*-\D* # match 0+ characters, a hyphen then 0+ non-digits
(\d+) # match 1+ digits in capture group 1
.*, # match 0+ characters then a comma
/x # free-spacing regex definition mode
通过以自由间距模式定义正则表达式,我们可以使其自文档化:
r = /
.* # match 0+ characters
-\D* # match a hyphen followed by 0+ non-digits
\K # forget everything matched so far
\d+ # match 1+ digits...
(?=.*,) # ...followed by 0+ characters then a comma (positive lookahead)
/x # free-spacing regex definition mode
或者
r = /
.*-\D* # match 0+ characters, a hyphen then 0+ non-digits
(\d+) # match 1+ digits in capture group 1
.*, # match 0+ characters then a comma
/x # free-spacing regex definition mode
谢谢你的回答!但是我遇到了这样的错误编译错误路径/to/file:undefined(?)sequence:/(?哦,对不起,我不知道你的Ruby版本。那是我的错!忘记写了。除了使用split“juraalunana11-126,Riga”。split(“-”)[-1]。split(“,”[0]
。字符类[\s*]
与空格或星号匹配。我认为这不是您想要的。请注意,在OP的示例中,逗号紧跟在要提取的数字之后,但问题没有指定没有中间字符(或者逗号和要提取的数字之间只有一个空格,甚至没有空格以外的字符)。感谢您的回答!但我遇到了如下错误编译错误路径/to/file:undefined(?…)序列:/(?哦,对不起,我不知道你的Ruby版本。那是我的错!忘记写了。除了使用split“Jura Alunana 11-126,Riga”。split(“-”)[-1]。split(“,”)[0]
。字符类[\s*]
匹配空格或星号。我认为这不是您想要的。请注意,在OP的示例中,逗号紧跟在要提取的数字之后,但问题没有指定没有中间字符(或者逗号和要提取的数字之间只有一个空格,甚至没有空格以外的字符)。谢谢!这也行,但数字也可以和字母连在一起,比如5A
,126B
等等。这个gsub忽略了它。但是感谢您的时间!@Marshmello然后,您需要替换(\d+)
与([\d|[a-z]]+)
,因此最终结果是/.-([\d|[a-z]]+),.*/i
。但这是一个正确的答案。请检查此红色链接谢谢!这也起作用,但数字也可以与字母连用,如5A
,126B
等等。此gsub忽略了它。但感谢您的时间!@Marshmello然后,您需要将(\d+)
替换为([\d|[a-z]]+)
,因此最终结果是/.-([\d|[a-z]]+),.*/i
。但这是一个正确的答案。检查这个红色链接为什么我们应该使用1
?它意味着什么?:)@Marshmello,具体地看方法的形式str[regexp,capture]
。为什么我们应该使用1
?它意味着什么?:)@Marshmello,具体请参见方法的形式str[regexp,capture]
。
str[r, 1]
#=> "126"
str1[r, 1]
#=> "126"