简体   繁体   English

正则表达式:如何使用之前的比赛进行匹配?

[英]Regular Expression: How to match using previous matches?

I am searching for string patterns of the form: 我正在搜索表单的字符串模式:

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

All of the Xs must be the same character and the A must not be an X. 所有X必须是相同的字符,A不能是X.

Note: I am not searching explicitly for Xs and As - I just need to find this pattern of characters in general. 注意:我没有明确搜索X和As - 我只需要找到这种字符模式。

Is it possible to build this using a regular expression? 是否可以使用正则表达式构建它? I will be implementing the search in Python if that matters. 如果重要的话,我将用Python实现搜索。

Thanks in advance! 提前致谢! -CS -CS

Update: 更新:

@rohit-jain's answer in Python @ rohit-jain在Python中的回答

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

@jerry's answer in Python @jerry在Python中的回答

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

You can try this: 你可以试试这个:

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

Break Up: 分手:

(\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

You can perhaps use this regex: 你可以使用这个正则表达式:

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

The first dot matches any character, then we call it back twice, make use of a negative lookahead to make sure there's not the captured character ahead and use another dot to accept any character once again, then 3 callbacks. 第一个点匹配任何角色,然后我们再回调两次,使用负向前瞻以确保前方没有捕获的角色并再次使用另一个点接受任何角色,然后再回调3次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM