使用正则表达式调用替换分隔符内的模式 [英] Replace patterns that are inside delimiters using a regular expression call

查看:63
本文介绍了使用正则表达式调用替换分隔符内的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要剪掉所有出现在长字符串中单引号内的模式--"(保留单引号外的那些).

I need to clip out all the occurances of the pattern '--' that are inside single quotes in long string (leaving intact the ones that are outside single quotes).

是否有 RegEx 方法可以做到这一点?(将它与语言中的迭代器一起使用是可以的).

Is there a RegEx way of doing this? (using it with an iterator from the language is OK).

例如以

"xxxx rt / $ 'dfdf--fggh-dfgdfg' ghgh- dddd -- 'dfdf' ghh-g '--ggh--' vcbcvb"

我应该得到:

"xxxx rt / $ 'dfdffggh-dfgdfg' ghgh- dddd -- 'dfdf' ghh-g 'ggh' vcbcvb"

所以我正在寻找一个可以从以下语言运行的正则表达式,如图所示:

So I am looking for a regex that could be run from the following languages as shown:

    +-------------+------------------------------------------+
    |  Language   |                  RegEx                   |
    +-------------+------------------------------------------+
    | JavaScript  |  input.replace(/someregex/g, "")         |
    | PHP         |  preg_replace('/someregex/', "", input)  |
    | Python      |  re.sub(r'someregex', "", input)         |  
    | Ruby        |  input.gsub(/someregex/, "")             |
    +-------------+------------------------------------------+

推荐答案

我从 Greg HewgillQn138522
它基于使用这个正则表达式(适应包含我正在寻找的模式):

I found another way to do this from an answer by Greg Hewgill at Qn138522
It is based on using this regex (adapted to contain the pattern I was looking for):

--(?=[^\']*'([^']|'[^']*')*$)

格雷格解释:

"这样做是使用非捕获匹配 (?=...) 来检查字符 x 是否在带引号的字符串中.它会查找一些非引号字符直到下一个引用,然后查找单个字符或带引号的字符组的序列,直到字符串末尾.这取决于您假设引号始终是平衡的.这也不是很有效."

"What this does is use the non-capturing match (?=...) to check that the character x is within a quoted string. It looks for some nonquote characters up to the next quote, then looks for a sequence of either single characters or quoted groups of characters, until the end of the string. This relies on your assumption that the quotes are always balanced. This is also not very efficient."

使用示例是:

  • JavaScript: input.replace(/--(?=[^']*'([^']|'[^']*')*$)/g, "")
  • PHP: preg_replace('/--(?=[^\']*'([^']|'[^']*')*$)/', "", input)
  • Python: re.sub(r'--(?=[^\']*'([^']|'[^']*')*$)', "", input)
  • Ruby: input.gsub(/--(?=[^\']*'([^']|'[^']*')*$)/, "")

我已经为 Ruby 测试了这个,它提供了想要的结果.

I have tested this for Ruby and it provides the desired result.

这篇关于使用正则表达式调用替换分隔符内的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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