[英]Combined regex pattern to match beginning and end of string and remove a separator character
[英]Regex: match a character except at the beginning of a string
我試圖從字符串中刪除一個字符,除非該字符位於字符串的開頭。
到目前為止,我的代碼如下所示:
def strip_string(value):
return re.sub(r"[^0-9\.]",'',value)
# strip_string('1-23') => '123'
我只想刪除不是第一個字符的破折號:
strip_string('-1-23') => '-123'
我知道如何定位作為第一個字符( r"^-"
)的破折號,但不知道相反。
是否有可能做到這一點,還是我需要以不同的方式去做?
從不在開頭的字符串中刪除字符的最簡單解決方案是使用(?!^)
/ (?!\\A)
負前瞻。 但是,您不能只使用re.sub(r"(?!^)[^0-9.]",'',value)
因為它也不會刪除非連字符字符,而您的場景暗示您希望在開始時只保留一個連字符。
因此,在 Python 3.5 和更新版本中,您可以使用(參見演示):
re.sub(r"^(-)|[^0-9.]+", r"\1", value)
或者,您可能會退回到
re.sub(r"(?!^)-|[^0-9.-]+", "", value) # This one is somewhat easier to understand
re.sub(r"-(?<!^-)|[^0-9.-]+", "", value) # This one is a bit more efficient
兩個-(?<!^-)
和(?!^)-
匹配-
這是不是在一個字符串的開頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.