从字符串中提取任意长度的数字的正则表达式

huangapple go评论68阅读模式
英文:

Regex to extract a number of any length from a string

问题

我正试图从一个字符串中提取一个数字(必定存在,长度任意)。该字符串实际上应以这个数字开头。我正在使用这个表达式:

[[\d]+YMD]

当输入为11M时,11被匹配两次,分别是1和1。在这个正则表达式中我漏掉了什么?我正在编写一个网页应用,但目前我正在使用在线工具测试这个正则表达式,结果是一样的。

英文:

I am trying to extract a number (Must exist, any length) from a string. The string should actually start with the number. I am using this expression:

[[\d]+YMD]

When given 11M as input, the 11 is matched twice as 1 then 1. What am I missing in this RegEx?

I am writing a web application, but for now, I am testing the RegEx online where I am getting the same results.

答案1

得分: 1

我猜你想要:

^\d+

^ = 字符串的开头
\d = 任意数字
+ = 1个或更多

英文:

I guess you want:

^\d+

^ = start of string
\d = any digit
+ = 1 or more

答案2

得分: 1

你可能最需要的是 + 量词,它的作用是:“匹配一次或多次,尽可能多次地匹配,根据需要回退”。

^\d+(D|M|Y) 将会确切地给你你似乎正在寻找的内容(只有在以数字开头并以 DMY 结尾时才匹配,确保至少有一个数字)。

链接:https://regex101.com/r/gWxkhd/2

英文:

You're most likely looking for the + quantifier which: "Matches between one and unlimited times, as many times as possible, giving back as needed".

^\d+(D|M|Y) will specifically give you what you seem to be looking for (making it only match if it starts with a number and ends with D, M, or Y, making sure there's at least 1 number.

https://regex101.com/r/gWxkhd/2

huangapple
  • 本文由 发表于 2020年9月23日 16:58:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64024415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定