如何删除字符串的一部分?
How to remove a part of string?
我是 Ruby 的新手,目前我正在尝试从 http 请求字符串中取出一部分。
要求:
POST /test/userRegistration?id=1234&name=John&address=UK
有没有办法用slice
、gsub
或其他方法取出"name=John&"
?
输出应该是 POST /test/userRegistration?id=1234&address=UK
注意:"name"参数的值每次都可以不同
谢谢
试试这个...
str = "POST /test/userRegistration?id=1234&name=John&address=UK"
str = str.sub(/&name=.+&/, '&')
str
=> "POST /test/userRegistration?id=1234&address=UK"
您可以使用 Addressable。这可能比自己编写一些字符串修改解决方案更容易。
您可以在字符串上使用 split
将其变成一个数组,然后 reject
name=
元素,然后 join
它们变成一个字符串:
"POST /test/userRegistration?id=1234&name=John&address=UK".split('&').reject { |e| e.start_with?('name=') }.join('&')
=> "POST /test/userRegistration?id=1234&address=UK"
还有其他可能性 here。
这不是简短的答案,但它可能是最可靠的,因为它实际上解析了 URL
require 'uri'
# parse
request = "POST /test/userRegistration?id=1234&name=John&address=UK".split
uri = URI request[1]
query = URI.decode_www_form uri.query
# modify the query params
query.delete_if { |param| param[0] == "name" }
# convert back to string
uri.query = URI.encode_www_form query
new_request = "#{request[0]} #{uri}"
我是 Ruby 的新手,目前我正在尝试从 http 请求字符串中取出一部分。
要求:
POST /test/userRegistration?id=1234&name=John&address=UK
有没有办法用slice
、gsub
或其他方法取出"name=John&"
?
输出应该是 POST /test/userRegistration?id=1234&address=UK
注意:"name"参数的值每次都可以不同
谢谢
试试这个...
str = "POST /test/userRegistration?id=1234&name=John&address=UK"
str = str.sub(/&name=.+&/, '&')
str
=> "POST /test/userRegistration?id=1234&address=UK"
您可以使用 Addressable。这可能比自己编写一些字符串修改解决方案更容易。
您可以在字符串上使用 split
将其变成一个数组,然后 reject
name=
元素,然后 join
它们变成一个字符串:
"POST /test/userRegistration?id=1234&name=John&address=UK".split('&').reject { |e| e.start_with?('name=') }.join('&')
=> "POST /test/userRegistration?id=1234&address=UK"
还有其他可能性 here。
这不是简短的答案,但它可能是最可靠的,因为它实际上解析了 URL
require 'uri'
# parse
request = "POST /test/userRegistration?id=1234&name=John&address=UK".split
uri = URI request[1]
query = URI.decode_www_form uri.query
# modify the query params
query.delete_if { |param| param[0] == "name" }
# convert back to string
uri.query = URI.encode_www_form query
new_request = "#{request[0]} #{uri}"