Ask Your Question
0

What is the regular expression in Python for digits that are repeated, but not necessarily in sequence?

asked 2021-07-03 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-05-11 03:00:00 +0000

devzero gravatar image

The regular expression in Python for digits that are repeated but not necessarily in sequence is:

(\d).*\1

This expression matches any digit that appears at least twice in a string.

  • (\d) captures a digit
  • .* matches any number of characters (including digits)
  • \1 matches the same digit captured by the first group

Example:

import re

string = "1234567891011"
pattern = re.compile(r'(\d).*\1')
matches = pattern.findall(string)

print(matches)   # Output: ['1']

In the above example, the pattern matches the digit '1' because it appears twice in the string: once as the first digit and again as part of the number '11'.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-07-03 11:00:00 +0000

Seen: 9 times

Last updated: May 11 '21