Home > OS >  match last integer from behind
match last integer from behind

Time:12-16

i have those strings

hello,world,1.fin
hello,world,start11.fin
hello,world,start11,then,end22.fin
hello,world,111,then,222,then,end333.fin
hello,world,111,then,222,then,end333threes.fin
hello,world,111,then,222,then,end333threes.fin444

and i need to match the endings numbers only before the . and after world, and i expect to get

1
11
22
333
333
333

i tried this but it does not match the last case ,world,.*?(\d )\. link then i tried this but it only get from begin ,world,.*?(\d ).*\. link

.fin is not static and it does change randomly to .fin444 or .444

CodePudding user response:

You can use

,world,(?:.*\D)?(\d )[^\W\d]*\.
,world,(?:.*\D)?(\d )[^\d.]*\.

See the regex demo.

Details:

  • ,world, - a fixed string
  • (?:.*\D)? - an optional sequence of any zero or more chars other than line break chars as many as possible and then a non-digit char
  • (\d ) - Group 1: one or more digits
  • [^\W\d]* (or, [a-zA-Z_]* can also be used, or even [^\d.]* to match any zero or more chars other than digit and a dot) - zero or more word chars excluding digits
  • \. - a . char.

CodePudding user response:

This should work

,world,.*?(\d )[^\d]*\.

See https://regex101.com/r/ilIsJb/1

  • Related