[英]what would the regular expression to extract the 3 from be?
I basically need to get the bit after the last pipe 我基本上需要在最后一个管道之后
"3083505|07733366638|3"
What would the regular expression for this be? 正则表达式是什么?
You can do this without regex. 您可以在不使用正则表达式的情况下执行此操作。 Here: 这里:
"3083505|07733366638|3".split("|").last
# => "3"
With regex: (assuming its always going to be integer values) 使用正则表达式:(假设其始终为整数值)
"3083505|07733366638|3".scan(/\|(\d+)$/)[0][0] # or use \w+ if you want to extract any word after `|`
# => "3"
Try this regex : 试试这个正则表达式:
.*\|(.*)
It returns whatever comes after LAST | 它返回LAST之后的所有内容。 . 。
I would use split
and last
, but you could do 我会使用split
和last
,但是你可以做
last_field = line.sub(/.+\|/, "")
That remove all chars up to and including the last pipe. 删除所有字符,直到最后一个管道。
You could do that most easily by using String#rindex : 您可以使用String#rindex最轻松地做到这一点 :
line = "3083505|07733366638|37"
line[line.rindex('|')+1..-1]
#=> "37"
If you insist on using a regex: 如果您坚持使用正则表达式:
r = /
.* # match any number of any character (greedily!)
\| # match pipe
(.+) # match one or more characters in capture group 1
/x # extended mode
line[r,1]
#=> "37"
Alternatively: 或者:
r = /
.* # match any number of any character (greedily!)
\| # match pipe
\K # forget everything matched so far
.+ # match one or more characters
/x # extended mode
line[r]
#=> "37"
or, as suggested by @engineersmnky in a comment on @shivam's answer: 或者,如@engineersmnky在对@shivam答案的评论中所建议:
r = /
(?<=\|) # match a pipe in a positive lookbehind
\d+ # match any number of digits
\z # match end of string
/x # extended mode
line[r]
#=> "37"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.