简体   繁体   中英

RegEx: Match after certain string is found otherwise select all

I want to select everything after & amazon - . If it is not found the whole string should be returned

String:

'adidas & amazon - cool shirt'

Best thing I came up is this:

(?(?=.*\\bamazon\\b)(\\bamazon\\b \\- (.+ *))|(.*))

But it also returns the amazon part.

The below regexes would work for you.

(?<=&\samazon\s-).*|^(?!.*&\samazon\s-).*$

(?<=&\\samazon\\s-).* matches all the characters which are just after to & space amazon space hyphen.

^(?!.*&\\samazon\\s-).*$ Matches the whole line which didn't have & amazon - string.

Change \\s to \\h if you want to deal only with the horizontal spaces.

OR

&\s*amazon\s*-\K.*|^(?!.*\samazon\s-).*$

\\K discards the previously matched characters from printing out at the final. This does the job of variable length positive lookebhind assertion.

DEMO

You can use this regex:

^(?|(?:.*?&\s*amazon\s*-\s*)(.*)|(.*))$

RegEx Demo

You matched data will be available in captured group #1.

Here (?|...) is a non-capturing group that makes sure that all the captured groups within this bracket start with same index ie 1.

This regex is using simple regex alternation. On LHS we have:

(?:.*?&\s*amazon\s*-\s*)(.*)

Which puts string after & amazon - into captured group #1

On RHS we just have:

(.*)

Which puts whole line into captured group #1 itself (due to use of (?|...)

Using the pattern you had before with a slight adjustment should work:

(?(?=.*&\s\bamazon\b).+)(.+\-\s(.+))

If you wanted this to match amazon regardless of where it was before - you could use:

(?(?=.*\bamazon\b).+)(.+\-\s(.+))

Examples:

https://regex101.com/r/kK3hP0/1 // matches & amazon before -

https://regex101.com/r/nG3yK8/1 // matches amazon anywhere before -

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