使用分组时如何使用 gsub 在 Ruby 正则表达式 (regex) 中反向引用? [英] How to backreference in Ruby regular expression (regex) with gsub when I use grouping?

查看:22
本文介绍了使用分组时如何使用 gsub 在 Ruby 正则表达式 (regex) 中反向引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想修补一些从网页中提取的文本数据.示例:

I would like to patch some text data extracted from web pages. sample:

t="First sentence. Second sentence.Third sentence."

第二句末尾的点后没有空格.这表明第 3 个句子在原始文档中位于单独的一行中(在 br 标签之后).

There is no space after the point at the end of the second sentence. This sign me that the 3rd sentence was in a separate line (after a br tag) in the original document.

我想使用这个正则表达式将 "字符插入到适当的位置并修补我的文本.我的正则表达式:

I want to use this regexp to insert " " character into the proper places and patch my text. My regex:

t2=t.gsub(/([.!?])([A-Z1-9])/,$1+"
"+$2)

但不幸的是它不起作用:NoMethodError: undefined method `+' for nil:NilClass"如何正确反向引用匹配的组?在 Microsoft Word 中非常简单,我只需要使用 1 和 2 符号即可.

But unfortunately it doesn't work: "NoMethodError: undefined method `+' for nil:NilClass" How can I properly backreference to the matched groups? It was so easy in Microsoft Word, I just had to use 1 and 2 symbols.

推荐答案

您可以使用 1 在替换字符串中反向引用(以匹配捕获组 1).

You can backreference in the substitution string with 1 (to match capture group 1).

t = "First sentence. Second sentence.Third sentence!Fourth sentence?Fifth sentence."
t.gsub(/([.!?])([A-Z1-9])/, "\1
\2") # => "First sentence. Second sentence.
Third sentence!
Fourth sentence?
Fifth sentence."

这篇关于使用分组时如何使用 gsub 在 Ruby 正则表达式 (regex) 中反向引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆