【问题标题】:Pattern matching with multiple nonspace characters与多个非空格字符的模式匹配
【发布时间】:2012-11-13 04:10:03
【问题描述】:

我有以下字符串数据:

data = "*****''[[dogs and cats]]''/n"

我想在 python 中使用正则表达式来提取字符串。所有数据都包含在双引号“”中。我使用了哪些通配符,以便获得以下信息:

print data.groups(1)
print data.groups(2)
print data.groups(3)

'dogs'
'and'
'cats'

编辑:到目前为止,我有一些很长的内容

  test = re.search("\\S*****''[[(.+) (.+) (.+)\\S]]''", "*****''[[dogs and cats]]''\n") 
  print test.group(1) 

【问题讨论】:

  • 你有没有尝试过自己解决这个问题?
  • 你说你想要的数据是双引号,但你的文本中唯一的双引号是在 python 字符串周围。你的意思是两个单引号''(而不是双引号")?是否应该始终忽略非字母字符(例如方括号)?
  • 另外,您可能希望接受之前问题的答案,以鼓励人们为您提供更多帮助!
  • 感谢您的意见。我仍在学习 StackOverflow 的诀窍。是的,@Austin Henley,我今天已经为此工作了一段时间。到目前为止,我的 thistest = re.search("\\S*****''[[(.+) (.+) (.+)\\S]]''", "*****''[[dogs and cats]]''\n") print test.group(1)
  • 您应该将该代码放入问题本身(您也可以在那里正确格式化它!)。当您使用该代码时会发生什么?您希望发生什么不同的事情?

标签: python regex string pattern-matching wildcard


【解决方案1】:

有些人在遇到问题时会想,“我知道,我会使用正则表达式。”现在他们有两个问题。” Jamie Zawinski

data = "*****''[[dogs and cats]]''/n"
start = data.find('[')+2
end = data.find(']')
answer = data[start:end].split()

print answer[0]
print answer[1]
print answer[2]

【讨论】:

  • 感谢您的洞察和报价!谢谢@Moshe
【解决方案2】:

很难确切地知道您在寻找什么,但我假设您正在寻找一个正则表达式,它可以解析出一个或多个由一些非字母数字字符包围的以空格分隔的单词。

data = "*****''[[dogs and cats]]''/n"

# this pulls out the 'dogs and cats' substring
interior = re.match(r'\W*([\w ]*)\W*', data).group(1)

words = interior.split()

print words
# => ['dogs', 'and', 'cats']

不过,这对您的要求做出了很多假设。根据您的具体需求,正则表达式可能不是最好的工具。

【讨论】:

    【解决方案3】:

    正如其他人所说,使用额外的split 步骤相当简单:

    data = "***rubbish**''[[dogs and cats]]''**more rubbish***"
    words = re.findall('\[\[(.+?)\]\]', data)[0].split() # 'dogs', 'and', 'cats'
    

    一个单一的表达也是可能的,但它看起来相当混乱:

    rr = r'''
        (?x)
        (\w+)
        (?=
            (?:
                (?!\[\[)
                .
            )*?
            \]\]
        )
    '''
    words = re.findall(rr, data) # 'dogs', 'and', 'cats'
    

    【讨论】:

    • 拆分是绕过它的好方法,尽管有点混乱。谢谢@thg435。
    猜你喜欢
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    相关资源
    最近更新 更多