Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby正则表达式方法_Ruby_Regex_String - Fatal编程技术网

Ruby正则表达式方法

Ruby正则表达式方法,ruby,regex,string,Ruby,Regex,String,我需要使用任何方法(如扫描或匹配)在ruby中获得预期的输出 输入字符串: http://test.com?t&r12=1&r122=1&r1=1&r124=1 http://test.com?t&r12=1&r124=1 预期: r12=1,r122=1,r1=1,r124=1 r12=1,r124=1 如何使用regex获得预期的输出?使用regex/r\d+=\d+/: 可以使用join获得字符串输出。在这里: "http://test.com?t&r12=1&r122=1

我需要使用任何方法(如扫描或匹配)在ruby中获得预期的输出

输入字符串:

http://test.com?t&r12=1&r122=1&r1=1&r124=1 http://test.com?t&r12=1&r124=1 预期:

r12=1,r122=1,r1=1,r124=1 r12=1,r124=1 如何使用regex获得预期的输出?

使用regex/r\d+=\d+/:

可以使用join获得字符串输出。在这里:

"http://test.com?t&r12=1&r122=1&r1=1&r124=1".scan(/r\d+=\d+/).join(',')
# => "r12=1,r122=1,r1=1,r124=1"
更新

如果URL包含可能在末尾包含r的其他参数,则可以使正则表达式更严格:

a = []
"http://test.com?r1=2&r12=1&r122=1&r1=1&r124=1&ar1=2&tr2=3&xy4=5".scan(/(&|\?)(r+\d+=\d+)/) {|x,y|  a << y}
a.join(',')
# => "r12=1,r122=1,r1=1,r124=1"

虽然输入字符串是带有查询的URL,但我会避免误报:

input = "http://test.com?t&r12=1&r122=1&r1=1&r124=1"
query_params = input.split('?').last.split('&')
#⇒ ["t", "r12=1", "r122=1", "r1=1", "r124=1"]
r_params = query_params.select { |e| e =~ /\Ar\d+=\d+/ }
#⇒ ["r12=1", "r122=1", "r1=1", "r124=1"]
r_params.join(',')
#⇒ "r12=1,r122=1,r1=1,r124=1"

它比只扫描原始输入中的任何regexp更安全。

如果确实需要正确使用regex,则需要使用如下regex:

puts "http://test.com?t&r12=1&r122=1&r1=1&r124=1".scan(/(?:http.*?\?t|(?<!^)\G)\&*(\br\d*=\d*)(?=.*$)/i).join(',')
puts "http://test.com?t&r12=1&r124=1".scan(/(?:http.*?\?t|(?<!^)\G)\&*(\br\d*=\d*)(?=.*$)/i).join(',')
puts "http://test.com?t&r12=1&r122=1&r1=1&r124=1".scan(/(?:http.*?\?t|(?<!^)\G)\&*(\br\d*=\d*)(?=.*$)/i).join(',')
puts "http://test.com?t&r12=1&r124=1".scan(/(?:http.*?\?t|(?<!^)\G)\&*(\br\d*=\d*)(?=.*$)/i).join(',')
r12=1,r122=1,r1=1,r124=1                                                                                                                                                                                                                               
r12=1,r124=1