【问题标题】:Regular Expression: How to match using previous matches?正则表达式:如何使用以前的匹配项进行匹配?
【发布时间】:2013-08-31 20:52:34
【问题描述】:

我正在寻找以下形式的字符串模式:

XXXAXXX 
# exactly 3 Xs, followed by a non-X, followed by 3Xs

所有的 X 必须是同一个字符,并且 A 不能是 X。

注意:我不是明确搜索 Xs 和 As - 我只需要找到一般的这种字符模式。

是否可以使用正则表达式来构建它?如果这很重要,我将在 Python 中实现搜索。

提前致谢! -CS

更新:

@rohit-jain 在 Python 中的回答

x = re.search(r"(\w)\1{2}(?:(?!\1)\w)\1{3}", data_str)

@jerry 在 Python 中的回答

x = re.search(r"(.)\1{2}(?!\1).\1{3}", data_str)

【问题讨论】:

  • 除了咨询下面的答案,不妨看看docs.python.org/2/library/re.html#regular-expression-syntax
  • 你可以使用x = re.search(r"(.)\1{2}(?!\1).\1{3}", data_str)来避免双重转义。
  • 甜蜜 - 谢谢杰瑞!
  • @CaymanEss 另外,我有点困惑为什么您将\n 置于否定前瞻中,因为它实际上破坏了正则表达式,请参阅this。如果您删除\n,它可以正常工作,请参阅this
  • @Jerry Typo...抱歉。 :(

标签: python regex python-2.7


【解决方案1】:

你可以试试这个:

(\w)\1{2}(?!\1)\w\1{3}

分手:

(\w)        # Match a word character and capture in group 1
\1{2}       # Match group 1 twice, to make the same character thrice - `XXX`
(?!\1)      # Make sure the character in group 1 is not ahead. (X is not ahead)
\w          # Then match a word character. This is `A` 
\1{3}       # Match the group 1 thrice - XXX

【讨论】:

  • 为了清楚起见,您可能想将“单词”改写为“单词字符”。
【解决方案2】:

你也许可以使用这个正则表达式:

(.)\1{2}(?!\1).\1{3}

第一个点匹配任何字符,然后我们将其回调两次,使用负前瞻来确保前面没有捕获的字符并使用另一个点再次接受任何字符,然后是 3 次回调。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    相关资源
    最近更新 更多