簡體   English   中英

正則表達式以匹配數字和算術運算符

[英]Regular expression to match number(s) and arithmetic operators

我正在尋找一個正則表達式,該表達式將匹配1到n次出現的數字,並且只出現一次算術運算符(僅允許+或-)

例如,它應匹配-123或123-或+123或123+

這就是我到目前為止

import re

number = "-123" 

if re.findall(r"[0-9]+[+|-]?", number): 
    return True
else:
    return False

嘗試這樣的事情:

In [55]: strs
Out[55]: '+123 abc 123 -123 123- 123+ 14 foo bar'

   #you need to escape '+'and '-' In order to search them   

In [56]: re.findall(r"\d+[\+|\-]{1}|[\-|\+]{1}\d+",strs)
Out[56]: ['+123', '-123', '123-', '123+']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM