正则表达式:如何从字符串的结尾开始查找

时间:2012-06-20 22:17:03

标签: regex uppercase right-to-left

我希望所有字符直到 大写,但从结束到开头。 (或从右到左)

  

blab blab 12 34这是一个考验!

我需要This is a test!

这是我设法找到的:

^.*?(?=[A-Z])

但它会返回blab blab 12 34

2 个答案:

答案 0 :(得分:2)

使用以下正则表达式:

irb(main):001:0> regex = /([A-Z][^A-Z]*)$/
irb(main):002:0> "blab blab 12 34 This is a test!".match regex
=> #<MatchData "This is a test!" 1:"This is a test!">

答案 1 :(得分:1)

好的,我会补充一下作为答案,可能会在以后将其发展为其他变种。简单的解决方案应该是......像:

 [A-Z][^A-Z]*$

测试(在Perl中):

 print $1 if 'blab blab 12 34 This is a test!' =~ /([A-Z][^A-Z]*)$/;

返回:

 This is a test!

要解决此问题,模式需要在字符串末尾锚定$)。

此致

RBO

相关问题