简体   繁体   English

R:正则表达式可以匹配方括号中的模式,但有例外

[英]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使事情变得轻松。

I think you can try this 我想你可以试试看

\[[^0x]+]

Explanation 说明

\\[ - Literally match [ character. \\[ -从字面上匹配[字符。

[^0x]+ - Match anything one or more time except 0x. [^0x]+ -匹配除0x以外的任何一次或多次时间。

] - Literally match ] character ] -从字面上匹配]字符

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM