小编chr*_*isk的帖子

使用^来匹配Python正则表达式中的行首

我正试图从Thomson-Reuters Web of Science中提取出版年份的ISI风格数据."Publication Year"的行看起来像这样(在一行的最开头):

PY 2015
Run Code Online (Sandbox Code Playgroud)

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

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

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

findyears()
Run Code Online (Sandbox Code Playgroud)

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

所以,我想只匹配一行开头的模式.通常我会^用于此目的,但r'^PY (\d\d\d\d)'未能匹配我的结果.另一方面,使用\n似乎做我想要的,但这可能会导致我的进一步复杂化.

python regex

19
推荐指数
2
解决办法
3万
查看次数

Perl Regex:无与伦比[正则表达式; 标有< - HERE

我有这个用于从文本中提取URL的小Perl脚本:

#!/usr/bin/perl

while ( <STDIN> )
{
if ( /(http|ftp|https):\/\/([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&amp;./~\+#]*[\w\-\@?^=%&amp;/~\+#])?/ )
{
print;
}
}
Run Code Online (Sandbox Code Playgroud)

当我在Textwrangler中搜索时,正则表达式工作正常,但是当我通过此脚本运行它时,我收到以下错误:

$ cat file.txt | perl myscript.pl
Unmatched [ in regex; marked by <-- HERE in m/(http|ftp|https)://([\w\-_]+(?:(?:\.[\w\-_]+)+))([ <-- HERE \w\-\.,@?^=%&amp;./ at myscript.pl line 5.
Run Code Online (Sandbox Code Playgroud)

regex perl

-1
推荐指数
1
解决办法
1319
查看次数

标签 统计

regex ×2

perl ×1

python ×1