ErAzOr
ErAzOr

Reputation: 57

Regex with optional word inside string

I try to Regex the following line (each word separated by one space):

Firstpartstring thisisoptional secondpartstring

I expect each string to match as group:

Group 1.    Firstpartstring
Group 2.    thisisoptional
Group 3.    secondpartstring

This is what I tried so far:

(.*?)\s(thisisoptional)?\s(.*)

Only problem is, if "thisisoptional" does not exist inside the string, I don't get any results.

I expect:

Group 1.    Firstpartstring
Group 2.    
Group 3.    secondpartstring

Please check this demo: https://regex101.com/r/YBlYXm/1

Can anyone get me in the right direction?

Thanks

Upvotes: 2

Views: 147

Answers (3)

Telmo Trooper
Telmo Trooper

Reputation: 5684

Can't you just group all non-whitespace characters with (\S+) and then remove the middle one if you get three matches?

Example of this regex running: https://regex101.com/r/IIyM5Z/1

Upvotes: 0

David
David

Reputation: 144

Your problem is that you are asking for two spaces (\s) in your Regex which does not match your case if thisisoptional is not included. The easy fix is to include the second space in your 2nd capturing group:

(.*?)\s(thisisoptional\s)?(.*)

this selects anything followed by thisisoptional then followed by anything

Upvotes: 3

blhsing
blhsing

Reputation: 106455

The space before the optional word should be made optional as well; otherwise it would require two spaces between the first and the last word to match:

(.*?)(?:\s(thisisoptional))?\s(.*)

https://regex101.com/r/YBlYXm/2

Upvotes: 2

Related Questions