【问题标题】:Converting regex python to javascript将正则表达式 python 转换为 javascript
【发布时间】:2017-12-25 18:38:00
【问题描述】:

我对 Regex 很陌生,我在 javascript 中搜索了很长时间,我希望有人回复了从 python 转换的 javascript 中的 regex 的详细解释。

import re

regex = r"""
    ^(
      (?P<ShowNameA>.*[^ (_.]) # Show name
        [ (_.]+
        ( # Year with possible Season and Episode
          (?P<ShowYearA>\d{4})
          ([ (_.]+S(?P<SeasonA>\d{1,2})E(?P<EpisodeA>\d{1,2}))?
        | # Season and Episode only
          (?<!\d{4}[ (_.])
          S(?P<SeasonB>\d{1,2})E(?P<EpisodeB>\d{1,2})
        | # Alternate format for episode
          (?P<EpisodeC>\d{3})
        )
    |
      # Show name with no other information
      (?P<ShowNameB>.+)
    )
    """

test_str = ("archer.2009.S04E13\n"
    "space 1999 1975\n"
    "Space: 1999 (1975)\n"
    "Space.1999.1975.S01E01\n"
    "space 1999.(1975)\n"
    "The.4400.204.mkv\n"
    "space 1999 (1975)\n"
    "v.2009.S01E13.the.title.avi\n"
    "Teen.wolf.S04E12.HDTV.x264\n"
    "Se7en\n"
    "Se7en.(1995).avi\n"
    "How to train your dragon 2\n"
    "10,000BC (2010)")

matches = re.finditer(regex, test_str, re.MULTILINE | re.VERBOSE)

for matchNum, match in enumerate(matches):
    matchNum = matchNum + 1

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

Regex101

【问题讨论】:

标签: javascript python regex


【解决方案1】:

遗憾的是,没有简单的方法将 Python 正则表达式转换为 Javascript 正则表达式,因为 Python 正则表达式比 Javascript 正则表达式更健壮。

Javascript 缺少功能性的东西,例如负向查找和递归,但它缺少更多的语法工具,例如冗长的语法和命名的捕获组。

常规捕获组 = ()
命名捕获组 = (?P&lt;ThisIsAName&gt;)

详细的正则表达式 = 'find me #this regex ignores comments and whitespace'
非详细正则表达式 = 'this treats whitespace literally'

因此,如果我们将您命名的捕获组转换为常规(编号)捕获组
如果我们将冗长的语法转换为常规语法。 那么该正则表达式将是有效的 Javascript 正则表达式,在 Javascript 中看起来像:
regex = /^((.*[^ (_.])[ (_.]+((\d{4})([ (_.]+S(\d{1,2})E(\d{1,2}))?|(?<!\d{4}[ (_.])S(\d{1,2})E(\d{1,2})|(\d{3}))|(.+))/

// group 2 = ShowNameA
// group 4 = ShowYearA
// group 6 = SeasonB
// group 7 = EpisodeC
// group 8 = ShowNameB

正如您所见,Javascript 版本非常丑陋,因为它没有冗长的语法或命名的捕获组。但是在这种情况下是功能等效的。

Javascript 没有 findall 的直接等价物,因此您必须制作/找到与之等价的东西。这是一篇文章,解释了几种这样的方法。 https://www.activestate.com/blog/2008/04/javascript-refindall-workalike

以后我也强烈推荐去 regexr.com 学习正则表达式,特别是 javascript 正则表达式。

【讨论】:

    猜你喜欢
    • 2011-10-02
    • 1970-01-01
    • 2019-05-11
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多