3

我正在搜索以下形式的字符串模式:

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)
4

2 回答 2

9

你可以试试这个:

(\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
于 2013-08-28T16:45:59.397 回答
4

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

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

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

于 2013-08-28T16:47:18.667 回答