简体   繁体   中英

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.

Try using ^ and $ to match the whole string:

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

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

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*)?$

正则表达式可视化

Working demo

在此处输入图片说明

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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