[英]R: Regex to match pattern in square brackets with exception
I have this string: 我有这个字符串:
“[DELW][0x00][BKSP][0x00][0x12][0xE0][0xF0][0xEF][DOWN][UP]asdkjaosdkj[ENTER]” “ [DELW] [0x00] [BKSP] [0x00] [0x12] [0xE0] [0xF0] [0xEF] [DOWN] [UP] asdkjaosdkj [ENTER]”
I want to remove all the keytab (in square bracket) starting with numbers like [0x00], [0xF0]. 我想删除所有从[0x00],[0xF0]之类的数字开始的键盘标签(在方括号中)。
Final result would be: “[DELW][BKSP][DOWN][UP]asdkjaosdkj[ENTER]” 最终结果将是:“ [DELW] [BKSP] [DOWN] [UP] asdkjaosdkj [ENTER]”
I thought about using str_replace but having a hard time coming up with regex that works. 我曾考虑过使用str_replace,但是很难找到能正常工作的正则表达式。 I would really appreciate all the help.
我真的很感谢所有帮助。 Thank you!
谢谢!
If your stuff to remove is always 0x
and two hex digits then: 如果要删除的内容始终为
0x
和两个十六进制数字,则:
> gsub("\\[0x..\\]","",s)
[1] "[DELW][BKSP][DOWN][UP]asdkjaosdkj[ENTER]"
Note the \\
needed to stop []
being special, and the \\\\
to get a real backslash into an R string. 注意停止
[]
所需的\\
是特殊的,而\\\\
要在R字符串中得到真实的反斜杠,请注意。
If you want to pull in the stringr
package you can do it with the same pattern: 如果要拉入
stringr
包,则可以使用相同的模式:
> stringr::str_replace_all(s, "\\[0x..\\]","")
[1] "[DELW][BKSP][DOWN][UP]asdkjaosdkj[ENTER]"
But base::gsub
keeps things light. 但是
base::gsub
使事情变得轻松。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.