python中的等价正则表达式是什么?

2024-06-08 01:32:28 发布

您现在位置:Python中文网/ 问答频道 /正文

PHP代码

<?php
    $str = "CSIR-National Botanical Research Institute, Plant Transgenic Laboratory, U.P., India. Electronic address: i.sanyal@nbri.res.in.";
    preg_match("/([A-Z][^\s,.]+[.]?\s[(]?)*(Hospital|University|Institute|Law School|School of|Academy|College)[^,\d]*(?=,|\d)/", $str, $org_arr);
    echo $org_arr[0];   
?>

输出

CSIR-National Botanical Research Institute

这个正则表达式从给定的PHP字符串中提取Hospital、University、Institute、School、Academy或College。我尝试在python中执行相同的正则表达式,但它不起作用。你知道吗

PYTHON代码

import re
line = "CSIR-National Botanical Research Institute, Plant Transgenic Laboratory, U.P., India. Electronic address: i.sanyal@nbri.res.in."
match = re.search(r'/([A-Z][^\s,.]+[.]?\s[(]?)*(Hospital|University|Institute|Law School|School of|Academy|College)[^,\d]*(?=,|\d)/', line)
print(match.group(0))

提供信息

Traceback (most recent call last): File "C:\Users\Ghost Rider\Documents\Python\temp.py", line 4, in print(match.group(0)) AttributeError: 'NoneType' object has no attribute 'group'


Tags: inmatchlinegroupphpschoolnationalresearch
1条回答
网友
1楼 · 发布于 2024-06-08 01:32:28

编辑:

很好的附加细节。因为模式与任何内容都不匹配,所以在None类型上出现错误;显示如何检查比解释更容易。。。你知道吗

所以让我们稍微改变一下你的例子,看看这是否符合你的要求。请注意图案上缺少前后斜杠(请参见下面的原文)。你知道吗

import re
txt = "CSIR-National Botanical Research Institute, Plant Transgenic Laboratory, U.P., India. Electronic address: i.sanyal@nbri.res.in."
# note: str is the string class type, python would happily let you assign that to a string literal.
print('txt={}'.format(txt))
pattern = r'([A-Z][^\s,.]+[.]?\s[(]?)*(Hospital|University|Institute|Law School|School of|Academy|College)[^,\d]*(?=,|\d)'
m = re.search(pattern, txt)
if m:
    print('found some things, groups={}'.format(m.groups()))
else:
    print('no match')

结果:

txt=CSIR-National Botanical Research Institute, Plant Transgenic Laboratory, U.P., India. Electronic address: i.sanyal@nbri.res.in.
found some things, groups=('Research ', 'Institute')

我认为PHP中的$org\u arr部分是在Python的m.groups()列表中设置的。你知道吗

原件:

也许可以在python中尝试不使用前导斜杠和尾部斜杠? 让我们从一个简单的模式开始。。。你知道吗

PHP示例

这些PHP docs显示了以下示例:

// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}

因为他们只是在php上搜索,所以斜杠看起来像是模式分隔符。你知道吗

在python中也是这个例子

在Python中是这样的(模式不是r'php,不是r'/php/')。你知道吗

import re
if re.match( r'php', 'PHP is the web scripting language of choice.', re.IGNORECASE):
    print('A match was found.')
else:
    print('A match was not found.')

更有用的方法是保留匹配对象,这样您就可以使用您的组。。。你知道吗

import re
m = re.match( r'(php)', 'PHP is the web scripting language of choice.', re.IGNORECASE)
if m:
    print('A match was found, group(1)={}'.format(m.group(1)))
else:
    print('A match was not found.')

相关问题 更多 >

    热门问题