【问题标题】:Splitting words before and after '/' in using Regex使用正则表达式在“/”之前和之后拆分单词
【发布时间】:2021-07-25 22:10:35
【问题描述】:

有以下字符串:

text = 'interesting/practical/useful'

我需要像interesting / practical / useful 一样使用正则表达式来拆分它。

我正在尝试这个

newText = re.sub(r'[a-zA-Z](/)[a-zA-Z]', ' \g<0> ', text)

但它会返回

interestin g/p ractica l/u seful

附:我在语料库中有其他文本也有不应该因为这个操作而改变的正斜杠,这是我正在寻找的正则表达式模式,特别是在'/' 之前和之后的字符。

【问题讨论】:

  • 你不能把'/'替换成' / '吗?
  • 用简单的方式来做:newText = ' / '.join('interesting/practical/useful'.split('/'))

标签: python regex python-re


【解决方案1】:

/ 之前和之后的字母使用环视,这样它们就不会包含在匹配中。

newText = re.sub(r'(?<=[a-zA-Z])/(?=[a-zA-Z])', ' \g<0> ', text)

【讨论】:

    【解决方案2】:

    我习惯这样做:

    newText = re.sub(r'([a-zA-Z])/([a-zA-Z])', '\1 / \2', text)
    

    \1\2是括号()中第一个和第二个成立表达式的引用

    在简单的英语中,它的意思是:查找任何字母、斜线、字母并用创建的字母、空格、斜线、空格和第二个创建的字母更改它们。

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多