[英]javascript regex - extract number from string
Given "1/2009 stay longer" or "34/1874 got to go", how can I get the digit right after the "/" using regex. 给定“ 1/2009停留时间更长”或“ 34/1874必须离开”,我如何使用正则表达式获取“ /”之后的数字。
'1/2009'.match(/\\d+\\/(\\d)\\d\\d\\d/g)[0]
is returning 1/2009
which is not what I want. '1/2009'.match(/\\d+\\/(\\d)\\d\\d\\d/g)[0]
返回1/2009
,这不是我想要的。 thx 谢谢
Your RegEx works, if you want single digit right after /
如果您想在/
后紧跟一位数字,则RegEx可以工作
Your regex \\d+\\/(\\d)\\d\\d\\d
will match digits /
then four digits and add first digit after slash in captured group. 您的正则表达式\\d+\\/(\\d)\\d\\d\\d
将匹配数字/
然后是四位数字,并在捕获的组中以斜杠添加第一位数字。 Note that 0th captured group will contain complete matched string. 请注意,第0个捕获的组将包含完整的匹配字符串。 g
flag is not necessary as there is only one instance of numbers in that pattern. g
标志不是必需的,因为在该模式中只有一个数字实例。
You can use this regex, but use first index to get the digit right after slash. 您可以使用此正则表达式,但可以使用第一个索引在斜杠后立即获取数字。
'1/2009'.match(/\d+\/(\d)\d\d\d/g)[1]
^ : Get me the value from first captured group.
And this regex can be optimized to below 这个正则表达式可以优化到以下
.match(/\/(\d)/)[1]
This will match the number followed by /
. 这将与/
后面的数字匹配。 And use the first captured group to extract the number. 并使用第一个捕获的组提取数字。
<input type="text" onblur="console.log(this.value.match(/\\/(\\d)/)[1])" />
To get all digits after /
要获取/
后的所有数字
Just add +
quantifier to \\d
in the captured group. 只需在捕获的组的\\d
中添加+
量词即可。
.match(/\/(\d+)/)[1]
Try 尝试
var string = "1/2009 stay longer"; console.log(string.match(/\\/(\\d+)/)[1]);
\\d+
matches one or more digits. \\d+
匹配一个或多个数字。 If you're only interested in capturing the digit right after /
, use string.match(/\\/(\\d)/
instead. 如果您只想在/
之后捕获数字,请使用string.match(/\\/(\\d)/
代替。
您还可以使用regExp对象的exec方法:
console.log(/\\d+\\/(\\d).*/.exec('1/2009')[1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.