Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何提取字符串中最右边的数字?_Ruby_Regex - Fatal编程技术网

Ruby 如何提取字符串中最右边的数字?

Ruby 如何提取字符串中最右边的数字?,ruby,regex,Ruby,Regex,我有这样的字符串: https://www.facebook.com/username_with_number_14/posts/101505775425654414 https://www.facebook.com/username/posts/101505775425654466 int1 = Regexp.new('.*?(\\d+)',Regexp::IGNORECASE).match()[1] ^.*?(\d+)$ 我需要在Ruby中提取字符串末尾的数字。在第一个字符串中,它是第

我有这样的字符串:

https://www.facebook.com/username_with_number_14/posts/101505775425654414
https://www.facebook.com/username/posts/101505775425654466
int1 = Regexp.new('.*?(\\d+)',Regexp::IGNORECASE).match()[1]
^.*?(\d+)$
我需要在Ruby中提取字符串末尾的数字。在第一个字符串中,它是第二个和最后一个数字,而在第二个字符串中,它是第一个、唯一的和最后一个数字

目前,我提取的数字如下:

https://www.facebook.com/username_with_number_14/posts/101505775425654414
https://www.facebook.com/username/posts/101505775425654466
int1 = Regexp.new('.*?(\\d+)',Regexp::IGNORECASE).match()[1]
^.*?(\d+)$
但是当它应用于第一个字符串时,它会提取用户名的数字部分,而不是所需的数字


如何才能使它在两个字符串上都工作?

对于我来说,regexp的工作方式如下:

https://www.facebook.com/username_with_number_14/posts/101505775425654414
https://www.facebook.com/username/posts/101505775425654466
int1 = Regexp.new('.*?(\\d+)',Regexp::IGNORECASE).match()[1]
^.*?(\d+)$
看这里:

试试这个

int1 = Regexp.new('.*\\/(\\d+)$',Regexp::IGNORECASE).match()[1]

$
匹配字符串的结尾。因此,我将从最后一个
/
到字符串末尾的所有数字放入捕获组1。

text=最后一个数字的意思是
10150575425654414
或仅
4
我不明白你想做什么你真正想做什么?我想我们有一些XY综合征。这假设数字总是在这个字符串的最末端。如果结尾可能有一些非数字字符,但仍要捕获数字,请使用^.*(\d+)\d*$
text = <<ENDTEXT
https://www.facebook.com/username_with_number_14/posts/101505775425654414
https://www.facebook.com/username/posts/101505775425654466
ENDTEXT

p text.lines.map{|line| line.scan(/\d+/).last}
#=> ["101505775425654414", "101505775425654466"]