ᴘᴀɴᴀʏɪᴏᴛɪs
ᴘᴀɴᴀʏɪᴏᴛɪs

Reputation: 7529

Regex matching abc:abc

I want to capture:

sometext
sometext:description

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

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626929

You can use the following regex:

 ^(\w+)(?:\:(\w+))?$

It will match both strings. See example.

Upvotes: 2

vks
vks

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

Avinash Raj
Avinash Raj

Reputation: 174706

Put the second pattern inside a non-capturing group and make it as optional.

([a-z]+)(?::([a-z]+))?

DEMO

Upvotes: 3

Related Questions