Ruby正则表达式从字符串中删除^ C字符(Ruby regex remove ^C character from string)

编程入门 行业动态 更新时间:2024-10-26 00:24:49
Ruby正则表达式从字符串中删除^ C字符(Ruby regex remove ^C character from string)

有一个文件具有控制B和控制C命令分隔文本字段。 看起来像:

"TEST\003KEY\002TEST\003KEY"

我试图创建一个与此匹配的正则表达式并将其删除。 我不确定为什么这个正则表达式不起作用:

"TEST\003KEY\002TEST\003KEY".gsub(/\00[23]/, ',')

There is a file that has control B and control C commands separating fields of text. It looks like:

"TEST\003KEY\002TEST\003KEY"

I tried to create a regex that will match this and remove it. I am not sure why this regex is not working:

"TEST\003KEY\002TEST\003KEY".gsub(/\00[23]/, ',')

最满意答案

请尝试以下方法:

"TEST\003KEY\002TEST\003KEY".gsub(/\002|\003/, ',')

这是在我的机器上的irb演示的:

$ irb 1.9.3p448 :007 > "TEST\003KEY\002TEST\003KEY".gsub(/\002|\003/, ',') => "TEST,KEY,TEST,KEY"

语法\002|\003表示“匹配字符文字\002或字符文字\003 ”。 原始问题\00[23]给出的表达式无效:这是字符文字\00 (空字符),后跟字符类[23] :即它匹配双字符序列。

您还可以使用[[:cntrl:]]字符类来匹配所有控制字符:

$ irb 1.9.3p448 :007 > "TEST\003KEY\002TEST\003KEY\005TEST".gsub(/[[:cntrl:]]/, ',') => "TEST,KEY,TEST,KEY,TEST"

Try the following:

"TEST\003KEY\002TEST\003KEY".gsub(/\002|\003/, ',')

Here it is demonstrated in irb on my machine:

$ irb 1.9.3p448 :007 > "TEST\003KEY\002TEST\003KEY".gsub(/\002|\003/, ',') => "TEST,KEY,TEST,KEY"

The syntax \002|\003 means "match the character literal \002 or the character literal \003". The expression given in the original question \00[23] is not valid: this is the character literal \00 (a null character) followed by the character class [23]: i.e. it matches two-character sequences.

You can also use the [[:cntrl:]] character class to match all control characters:

$ irb 1.9.3p448 :007 > "TEST\003KEY\002TEST\003KEY\005TEST".gsub(/[[:cntrl:]]/, ',') => "TEST,KEY,TEST,KEY,TEST"

更多推荐

本文发布于:2023-07-28 04:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1300400.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符   正则表达式   Ruby   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!