Reputation: 7529
I want to capture:
sometext
sometext:description
sometext:description
I want to capture both
sometext
and description
(I can do that using ([a-z]+):([a-z]+)
)sometext
I want to capture only sometext
(I can do that using ([a-z]+)
)How can I combine the two expressions together? That if and only if the input is of the form a:b
I'll capture both, else just a
I've tried:
((([a-z]+):([a-z]+)) | ([a-z]+))
But it won't capture 'abcde'
Upvotes: 1
Views: 1590
Reputation: 626929
You can use the following regex:
^(\w+)(?:\:(\w+))?$
It will match both strings. See example.
Upvotes: 2
Reputation: 67968
([a-z]+):([a-z]+)|([a-z]+)
Your regex is working for me.See demo.
https://regex101.com/r/sJ9gM7/62
((([a-z]+):([a-z]+)) | ([a-z]+))
^^^^
These spaces are causing the problem.
Upvotes: 1
Reputation: 174706
Put the second pattern inside a non-capturing group and make it as optional.
([a-z]+)(?::([a-z]+))?
Upvotes: 3