简体   繁体   中英

Regex group match if present

My input string is:

/234243/source_path/a/b/c.test

or something like:

/234243/source_path/a/b/c.test/check_w123

I want a regex to match substrings starting with source and check with the result like:

  • source : source_path/a/b/c.test/
  • check : check_w123

using a regex like /(?<source>source.*)(?<check>check.*)/ without ? in the last group.

My regex is:

/(?<source>source.*)(?<check>check.*)?/

My Result is:

  • source : source_path/a/b/c.test/check_w123
  • check : nil

Just turn .* inside the first source group into it's non-greedy form. And don't forget to add end of the line anchor.

(?<source>source.*?)(?<check>check.*)?$

DEMO

(?<source>source.*?(?!.*\/))(?<check>check.*)?

Try this.See demo.

https://regex101.com/r/rU8yP6/11

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