Renae Lider
Renae Lider

Reputation: 1024

Only match if all characters belong to what is specified

Match 3.14529
Match -255.34
Match 128
Match 1.9e10
Match 123,340.00
Skip 720p

In order to skip the last one, I tried this regex:

([\d\.e\-,])

The criteria is this: If every character in the string is either a digit(\d) or a dot(.) or exponent (e) or negative (-) or a comma(,), match the string, if any other characters are present skip the entire string.

Problem is that the last one has a "p" in it, and it must be ignored. However, due to the digits in front of it (720), it is also included in the match.

Upvotes: 0

Views: 62

Answers (2)

Federico Piazza
Federico Piazza

Reputation: 30985

You have to leverage anchors ^ and $, however if you use:

^[\d\.e\-,]+$

...this will allow matches like:

.e.e.e---,,
1,.2,2e.eee
.....
---
etc...

I can come up with this regex:

^-?\d{1,3}(,\d{3})*\.?\d*(e\d*)?$

Regular expression visualization

Working demo

enter image description here

You can use a code like this:

import re
p = re.compile(ur'^-?\d{1,3}(,\d{3})*\.?\d*(e\d*)?$', re.MULTILINE)
test_str = u"Match\n3.14529\n-255.34\n128\n1.9e10\n123,340.00\n\nSkip \n720p"

re.findall(p, test_str)

Upvotes: 3

ciscoheat
ciscoheat

Reputation: 3947

Try using ^ and $ to match the whole string:

^[\d\.e\-,]+$

^ matches the beginning of a string, $ the end.

Upvotes: 3

Related Questions