简体   繁体   中英

How to get everything before the second-to-last occurrence with a regex?

I need everything that's behind the second-to-last comma and space of my string.

Example:

input: Jan 23, 2023, October 23, 2022, 2 October 23, 2022, Jan 23, 2023

output: Jan 23, 2023, October 23, 2022, 2 October 23, 2022

I tried this but this gives me the contrary result and it doesn't handle the space.

([^,]+),[^,]+$

https://regex101.com/r/IPFj0y/1

This seems to do the trick in the first capturing group:

(.*)(?=(, .*, ))

Explanation: first capture group captures everything up until the positive lookahead group (?=). Inside the positive lookahead I added the second to last rule you seeked, which is comma and space followed by anything and then another comma and space.

You can match using this regex:

(.*\b\d{4}),.*

and replace with '$1 .

RegEx Demo

RegEx Breakup:

  • (.*\b\d{4}) : Match any text until last 4 digits. Due to greedy nature of .* quantifier it will match longest possible string before matching last 4 digits
  • , : Match a comma
  • .* : Match everything till end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM