正则表达式以匹配不带点号(“。”)的数字 [英] Regex to match a digit not followed by a dot(".")
问题描述
我有一个字符串
字符串1 (不包括引号)->我的车号是# 8746253 实际上很酷
string 1(excluding the quotes) -> "my car number is #8746253 which is actually cool"
条件-数字8746253可以是任意长度,并且< br>
-数字也可以紧随行尾。
conditions - The number 8746253, could be of any length and
- the number can also be immediately followed by an end-of-line.
我要分组出 8746253 ,不应在其后加上点。。
我尝试过,
I want to group-out 8746253 which should not be followed by a dot "."
I have tried,
。*#(\d +)[^。]。*
.*#(\d+)[^.].*
这可以肯定地得到数字,但是即使有一个点也可以匹配,因为[。^]将匹配数字的最后一位(例如, 3 (在以下情况下)
This will get me the number for sure, but this will match even if there is a dot, because [.^] will match the last digit of the number(for example, 3 in the below case)
字符串2 (不包括引号)->地球距离# 8746253.Kms ,这很远
string 2(excluding the quotes) -> "earth is #8746253.Kms away, which is very far"
我只想匹配 字符串1 类型,而不是 字符串2 类型。
I want to match only the string 1 type and not the string 2 types.
推荐答案
要匹配#
之后没有后跟点的任意数量的数字,请使用
To match any number of digits after #
that are not followed with a dot, use
(?<=#)\d++(?!\.)
++
是所有格量词,将使正则表达式成为正则表达式引擎只会在最后一个匹配的数字之后检查前瞻(?! \。)
,并且如果后面有一个点,则不会回溯。因此,如果某个数字块中的最后一个数字后面没有数字,则整个比赛将失败。
The ++
is a possessive quantifier that will make the regex engine only check the lookahead (?!\.)
only after the last matched digit, and won't backtrack if there is a dot after that. So, the whole match will get failed if there is a dit after the last digit in a digit chunk.
请参见 regex演示
要匹配整行并将数字放入捕获组#1中:
To match the whole line and put the digits into capture group #1:
.*#(\d++)(?!\.).*
请参见此regex演示。或没有前瞻性的版本:
See this regex demo. Or a version without a lookahead:
^.*#(\d++)(?:[^.\r\n].*)?$
请参见另一个演示。在最后一个版本中,数字块只能跟一个不是的char的可选序列。
,CR和LF后跟除换行符((?:[^。\r\n]。*)?
)之外的任何0+字符,然后是字符串的末尾( $
)。
See another demo. In this last version, the digit chunk can only be followed with an optional sequence of a char that is not a .
, CR and LF followed with any 0+ chars other than line break chars ((?:[^.\r\n].*)?
) and then the end of string ($
).
这篇关于正则表达式以匹配不带点号(“。”)的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!