Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.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
Regex 如何改进这个正则表达式?_Regex_Python 2.7 - Fatal编程技术网

Regex 如何改进这个正则表达式?

Regex 如何改进这个正则表达式?,regex,python-2.7,Regex,Python 2.7,我有一个字符串列表,如下所示: /soccer/poland/ekstraklasa-2008-2009/results/ /soccer/poland/orange-ekstraklasa-2007-2008/results/ /soccer/poland/orange-ekstraklasa-youth-2010-2011/results/ 从每个字符串中,我想取一个中间部分,分别得出: ekstraklasa orange ekstraklasa orange ekstraklasa y

我有一个字符串列表,如下所示:

/soccer/poland/ekstraklasa-2008-2009/results/
/soccer/poland/orange-ekstraklasa-2007-2008/results/
/soccer/poland/orange-ekstraklasa-youth-2010-2011/results/
从每个字符串中,我想取一个中间部分,分别得出:

ekstraklasa
orange ekstraklasa
orange ekstraklasa youth
我的代码在这里完成了这项工作,但感觉它可以用更少的步骤完成,而且可能只需要使用regex

name = re.search('/([-a-z\d]+)/results/', string).group(1) # take the middle part
name = re.search('[-a-z]+', name).group()                  # trim numbers
if name.endswith('-'):
    name = name[:-1]                                       # trim tailing `-` if needed
name = name.replace('-', ' ')

有人知道如何改进吗?

这个正则表达式应该可以完成以下工作:

/(?:\/\w+){2}\/([\w\-]+)(?:-\d+){2}/
说明:

  • (?:\/\w+{2}
    -吃由
    /
  • \/
    -吃下一个
    /
  • ([\w\-]+)
    -匹配连字符的单词字符(这是我们正在寻找的)
  • (?:-\d+{2}
    -吃掉我们要找的零件后面的连字符和数字

结果是在第一个匹配组中

我无法测试它,因为我没有使用python,但我会使用如下表达式

^(/soccer/poland/)([a-z\-]*)(.*)$

这个表达式在开始时类似于“/soccer/poland/”,而不是“所有带有a到z(小)或-”以及字符串的其余部分

而不是第二组

组应包含以下字符串:

  • /soccer/poland/
  • 橙色ekstraklasa青年-
  • 2010-2011/results/
然后简单地用“”替换“-”并在其后修剪空格

注:如果您使用regex101.com,例如,您需要转义/只使用一行字符串! 表情

^(\/soccer\/poland\/)([a-z\-]*)(.*)$
还有一排你的绳子

/soccer/poland/orange-ekstraklasa-youth-2010-2011/results/

如果你不想用这个词来形容足球和波兰,那就用这个词

^(\/[a-z]*\/[a-z]*\/)([a-z\-]*)(.*)$

谢谢你的尝试。但是我在regex101.com上测试了它,没有发现任何匹配项。你测试过吗?我在regex101.com上运行了一个测试,但没有发现匹配项。此外,第一个正则表达式过于严格,除了
足球/波兰
之外,还会有其他名称。
^(\/[a-z]*\/[a-z]*\/)([a-z\-]*)(.*)$