Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python正则表达式中使用“^”匹配行首_Python_Regex - Fatal编程技术网

在Python正则表达式中使用“^”匹配行首

在Python正则表达式中使用“^”匹配行首,python,regex,Python,Regex,我试图从汤森路透科学网中提取ISI风格的出版年份数据。“出版年”的行如下所示(在行首): 对于我正在编写的脚本,我定义了以下正则表达式函数: import re f = open('savedrecs.txt') wosrecords = f.read() def findyears(): result = re.findall(r'PY (\d\d\d\d)', wosrecords) print result findyears() 然而,这会产生假阳性结果,因为模式可

我试图从汤森路透科学网中提取ISI风格的出版年份数据。“出版年”的行如下所示(在行首):

对于我正在编写的脚本,我定义了以下正则表达式函数:

import re
f = open('savedrecs.txt')
wosrecords = f.read()

def findyears():
    result = re.findall(r'PY (\d\d\d\d)', wosrecords)
    print result

findyears()
然而,这会产生假阳性结果,因为模式可能出现在数据的其他地方


所以,我只想匹配一行开头的模式。通常我会为此使用
^
,但是
r'^PY(\d\d\d\d)
无法匹配我的结果。另一方面,使用
\n
似乎可以实现我想要的功能,但这可能会给我带来更多的麻烦。

使用
重新搜索
重新搜索

import re
p = re.compile(r'^PY\s+(\d{4})', re.M)
test_str = "PY123\nPY 2015\nPY 2017"
print(re.findall(p, test_str)) 

说明

  • ^
    -行的开始(由于
    re.M
  • PY
    -Literal
    PY
  • \s+
    -1个或多个空格
  • (\d{4})
    -包含4位数字的捕获组

在这种特殊情况下,不需要使用正则表达式,因为搜索的字符串始终为“PY”,并且应该位于行的开头,因此可以使用
string.find
来执行此作业。
find
函数返回在给定字符串或行中找到子字符串的位置,因此如果在字符串开头找到子字符串,则返回值为0(-1,如果根本找不到),即:

也许去掉空白是个好主意,例如:

In [14]: '  PY 2015'.find('PY')
Out[14]: 2

In [15]: '  PY 2015'.strip().find('PY')
Out[15]: 0
下一步,如果只对该年感兴趣,则可以使用split提取,即:

In [16]: '  PY 2015'.strip().split()[1]
Out[16]: '2015'

用于更改
^
的语义:
re.findall(r'^PY(\d\d\d\d)'、wosrecords、re.MULTILINE)
是的,这也应该有效。我错过的是re.M或re.MULTILINE标志,我不知道它会影响^。实际上,这是
re.M
的唯一功能:强制
^
$
分别在行首和行尾(在
\n
之前)匹配。
In [12]: 'PY 2015'.find('PY')
Out[12]: 0

In [13]: ' PY 2015'.find('PY')
Out[13]: 1
In [14]: '  PY 2015'.find('PY')
Out[14]: 2

In [15]: '  PY 2015'.strip().find('PY')
Out[15]: 0
In [16]: '  PY 2015'.strip().split()[1]
Out[16]: '2015'