Arvind Ganesh
Arvind Ganesh

Reputation: 31

Regexing help in python

I am wondering if there is an efficient way to check if a number is in the format 1_2_3_4_5_6_7_8_9_0 , where the '_' is a number. For Example,

1929374254627488900

My initial though was string indexing, but I quickly discovered that it was too slow. Is there a better way using regexing in python?

Thanks in advance, Arvind

Upvotes: 0

Views: 60

Answers (3)

John1024
John1024

Reputation: 113994

Let's define a string to test:

>>> q = '1929374254627488900'

Now, let's test it:

>>> q[::2] == '1234567890'
True

That matches. Now, let's try one that doesn't match:

>>> q = '1929374254627488901'
>>> q[::2] == '1234567890'
False

This works because q[::2] returns every other character in the string and those are the characters that you are interested in testing.

Additional tests

Suppose we are unsure if the string is all numbers. In that case, we add a test. This should pass:

>>> q = '1929374254627488900'
>>> q[::2] == '1234567890' and q.isdigit()
True

While, because of the a, this should fail:

>>> q = '19293742546274889a0'
>>> q[::2] == '1234567890' and q.isdigit()
False

We can also test for correct length:

>>> q = '1929374254627488900'
>>> q[::2] == '1234567890' and q.isdigit() and len(q) == 19
True

Upvotes: 1

Hackaholic
Hackaholic

Reputation: 19771

Here you go, indexing is fast O(1)

>>> my_number = 1929374254627488900
>>> int(str(my_number)[1::2])
997242480 # actual number
>>> int(str(my_number)[0::2])
1234567890     #format

Upvotes: 0

Abhijit
Abhijit

Reputation: 63787

My initial thought was string indexing, but I quickly discovered that it was too slow

Most possibly you are not using the right approach

You can always use regex but, string indexing with strides can have better performance than using regex

st = "1929374254627488900"
st[::2] == "1234567890"
Out[93]: True

Upvotes: 0

Related Questions