[英]regex for digits and plus/minus sign
My problem is that I can't figure out a way to define a regex that would print digits in case there is only +, -, [ or whitespace in front of them and only bracket or whitespace after.我的问题是我无法想出一种方法来定义一个正则表达式来打印数字,以防它们前面只有 +、-、[ 或空格,后面只有括号或空格。 In addition if there is minus it should be printed.
此外,如果有减号,则应打印。 I have tried looking for similar cases and spent quite sometime with the problem but haven't been able to come up with an answer.
我曾尝试寻找类似的案例,并花了很长时间解决这个问题,但一直未能找到答案。
So what I have at the moment is:所以我现在拥有的是:
\b([+-]?[0-9]+)\b
And it should print out 16, -55, and +18 from the following:它应该从以下打印出 16、-55 和 +18:
[16 ] [a44] [fg] [230+] [+-50] [ -55 ]x [+18]aff
At the moment it prints in addition 50 and 230 which it shouldn't.目前它还打印了不应该打印的 50 和 230。 I would be grateful for any tips.
我将不胜感激任何提示。
You may use您可以使用
(?<![\w+-])[+-]?\d+(?![\w+-])
See the regex demo查看正则表达式演示
Details细节
(?<![\w+-])
- a negative lookbehind that fails the match if, immediately to the left of the current position, there is a word, -
or +
char (?<![\w+-])
- 如果紧邻当前 position 的左侧有一个单词-
或+
字符,则匹配失败[+-]?
- an optional +
or -
+
或-
\d+
- 1+ digits \d+
- 1+ 位(?![\w+-])
- a negative lookahead that fails the match if, immediately to the right of the current position, there is a word, -
or +
char. (?![\w+-])
- 如果在当前 position 的右侧有一个单词-
或+
字符,则匹配失败。import re
rx = r"(?<![\w+-])[+-]?\d+(?![\w+-])"
s = "[16 ] [a44] [fg] [230+] [+-50] [ -55 ]x [+18]aff"
print( re.findall(rx, s) )
# => ['16', '-55', '+18']
Indeed \b
matches any non-word character.确实
\b
匹配任何非单词字符。 +
is a non-word character, so +
in 230+
and +
in +-50
match ! +
是一个非单词字符,所以+
中的230+
和+
+-50
中的 + 匹配!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.