Regexp to strip off only ending numbers or chars after _ at the end of a string

StackOverflow https://stackoverflow.com/questions/13515608

  •  01-12-2021
  •  | 
  •  

문제

I'd like to have a regexp in java to only strip off numbers if they are at the end of the string and everything after the underscore.

1) massi_xxx -> massi
2) massi_12121 -> massi
3) massi123 -> massi
4) 123massi1 -> 123massi

I found that
(?=[0-9_]).* works fine for 1,2,3 use case but not for 4) Any idea on how to refine it?

Thanks M.

도움이 되었습니까?

해결책

The following regex should work for most flavors:

(?:_.*|\d*)$

We match either _ followed by anything until the end of the string. Or we match a bunch of digits until the end of string. (The end of string is represented by the anchor $)

Working demo.

Some flavors might choke upon the ?: which is really just an optimization. You can as well leave it out.

다른 팁

(_.*|\d+)$ will match underscore followed by anything or digits at the end of a string. Does that meet your requirement? (I used http://www.regextester.com/ for testing.)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top