简体   繁体   English

正则表达式匹配字符串末尾的数字

[英]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 :小数点后的1位数或更多位数
  • $ : 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: 几个问题:

  • side note : the dash doesn't need to be escaped; 旁注 :破折号不需要逃脱; it's only special in character classes (eg [az] ). 它仅在字符类中很特殊(例如[az] )。
  • the dot is special; 特殊的; it means "match any character". 它的意思是“匹配任何字符”。 You'll want to escape it: \\. 您将要转义它: \\.
  • \\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"). 实际上意味着:至少匹配一位,但是如果正则表达式在模式的这一部分之后继续进行,请尝试尽早匹配其余的正则表达式(“ 惰性 ”或“非贪婪匹配”)。 In your case this ? 在您的情况下? just does nothing. 什么也没做。 To make those digits truly optional, use \\d* . 要使这些数字真正可选,请使用\\d*
  • Finally, you might want to make the decimal point and the subsequent digits optional as a group: (\\.\\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.

On jsfiddle jsfiddle上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM