我的字符串包含\xXXXX
和\uXXXX
:
str = "\nDefault\nRouterRandom=\x9Db\u0012\xD3,\x92r\xFC o\u007F\x9B+\u0005I`\nWebInit=1\n"
我想删除内容:
"RouterRandom=\x9Db\u0012\xD3,\x92r\xFC o\u007F\x9B+\u0005I`\n"
如何匹配字符串或将其删除?我试过了:
content = str.sub(/RouterRandom=.*WebInit/, "")
它返回错误:
E:/Automation/experiment/ruby_test/string_test.rb:119:in `sub': invalid byte sequence in UTF-8 (ArgumentError)
from E:/Automation/experiment/ruby_test/string_test.rb:119:in `block in <top (required)>'
from E:/Automation/experiment/ruby_test/string_test.rb:110:in `open'
from E:/Automation/experiment/ruby_test/string_test.rb:110:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
答案 0 :(得分:0)
由于字符串中的字符无效,您收到invalid byte sequence
。您可以先替换字符串中的无效字符:
content = str.encode( 'UTF-8', invalid: :replace )
然后按换行分开:
content = content.split( "\n" )
按索引删除数组中的违规元素:
content.delete_at( 2 )
然后最终将数组重新加入换行符分隔的字符串:
new_str = content.join( "\n" )
# => "\nDefault\nWebInit=1"