[英]RegEx match a number at the end of a string
I'm trying to match a number at the end of a string, using a regex. 我正在尝试使用正则表达式来匹配字符串末尾的数字。 For example, the string might look like:
例如,字符串可能看起来像:
var foo = '101*99+123.12'; // would match 123.12
var bar = '101*99+-123'; // would match -123
var str = '101*99+-123.'; // would match -123.
This is what I've got so far, but it seem to match the entire string if there is no decimal point: 这是我到目前为止的结果,但是如果没有小数点,它似乎可以匹配整个字符串:
foo.match(/\-?\d+.?\d+?$/);
I take this to mean: 我的意思是:
\\-?
: optional "-" symbol \\d+
: 1 or more digits \\d+
:1个或多个数字 .?
: optional decimal point \\d+?
: optional 1 or more digits after decimal point $
: match at the end of the string $
:在字符串末尾匹配 What am I missing? 我想念什么?
.
matches any character. 匹配任何字符。 You need to escape it as
\\.
您需要将其转义为
\\.
Try this: 尝试这个:
/-?\d+\.?\d*$/
That is: 那是:
-? // optional minus sign
\d+ // one or more digits
\.? // optional .
\d* // zero or more digits
As you can see at MDN's regex page , +?
如您在MDN的正则表达式页面上看到的 ,
+?
is a non-greedy match of 1 or more, not an optional match of 1 or more. 是1或更大的非贪婪匹配,而不是1或更大的可选匹配。
Several issues: 几个问题:
[az]
). [az]
)。 \\.
\\.
\\d+?
actually means: match at least one digit, but if the regex goes on after that part of the pattern, try to match the remaining regex as early as possible (" lazy " or "non-greedy matching"). ?
?
just does nothing. \\d*
. \\d*
。 (\\.\\d+)?
(\\.\\d+)?
Executive summary: /-?\\d+(\\.\\d+)?$/
执行摘要:/-?
/-?\\d+(\\.\\d+)?$/
This should do the job /-?\\d+\\.?\\d*$/
这应该完成工作
/-?\\d+\\.?\\d*$/
result = subject.match(/-?\d+\.?\d*$/mg);
If the pattern is always x*y+z
then you could do this alternatively without a regex like so. 如果模式始终是
x*y+z
那么您可以选择不使用正则表达式来执行此操作。
var foo = '101*99+123.12'; // would match 123.12
var bar = '101*99+-123'; // would match -123
var str = '101*99+-123.'; // would match -123.
function getLastNumber(string) {
return string.split("+")[1];
}
console.log(getLastNumber(foo));
console.log(getLastNumber(bar));
console.log(getLastNumber(str));
Output 输出量
123.12
-123
-123.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.