红宝石gsub和订购替换如preg_replace

时间:2018-06-20 14:12:54

标签: ruby regex gsub

我具有php的以下功能

pattern = "/^(.+)\/s3\/aws4_request\\n.+$/s"
result = preg_replace(pattern,'$1/s3aws4_request'."\n".$hashedCanonicalRequest, $rawStringToSign);

红宝石

pattern = /^(.+)\/s3\/aws4_request\\n.+$/
result = params[:headers].gsub(pattern, "$1/s3/aws4"+"\n"+hashed)

如何在gsub中进行订购?我的意思是那些$ 1和$?你能解释一下吗?

完整更新

Parameters: {"headers"=>"AWS4-HMAC-SHA256\n20180620T172236Z\n20180620/eu-west-2/s3/aws4_request\nPOST\n/65f9a73f-f7f5-4e9e-8e0e-e1c6afaa83c9.jpg\nuploads="}
hashedCanonicalRequest = "test"
pattern_two = /^(.+)\/s3\/aws4_request\n.+$/
stringToSign =  params[:headers].gsub(pattern_two, '\1/s3/aws4_request'+"\n"+ hashedCanonicalRequest)
# "AWS4-HMAC-SHA256\n20180620T172051Z\n20180620/eu-west-2/s3/aws4_request\ntest\n/65f9a73f-f7f5-4e9e-8e0e-e1c6afaa83c9.jpg\nuploads="

1 个答案:

答案 0 :(得分:1)

使用\1等替换所捕获的组:

str = 'http://s3.amazonaws.com/prod/s3/aws4_request\nfoo'
pattern = /^(.+)\/s3\/aws4_request\\n.+$/
str.gsub(pattern, '\1/s3/aws4'+"\n")
# => "http://s3.amazonaws.com/prod/s3/aws4\n"

修改

 str = "AWS4-HMAC-SHA256\n20180620T172236Z\n20180620/eu-west-2/s3/aws4_request\nPOST\n/65f9a73f-f7f5-4e9e-8e0e-e1c6afaa83c9.jpg\nuploads="

 pattern =  /^(.+)\/s3\/aws4_request.*/m # .* to capture everythign after aws_request, m for multiline, let's regex scan across \n
 str.gsub(pattern, '\1/s3/aws4'+"\n")
 #=> "AWS4-HMAC-SHA256\n20180620T172236Z\n20180620/eu-west-2/s3/aws4\n"