patrik
patrik

Reputation: 4558

How to match something, which may or may not be available in regex?

I found this little thing online (.*)((?::))((?:[0-9]+))$ which will split an IP address and port.

eg.

[ab:cd::0]:22
host.domain.com:443
1.2.3.4:22

However, it requires this format and does not care for other formats.

Due to this I made a minor change (.*)((?::))((?:[0-9]+))?$, which will then only include port if available.

Now, there are three kinds of formats available for URIs:

host.domain.com
host.domain.com: 
host.domain.com:port

I am kind of lost here. because while adding a ? for the second group (.*)((?::))?((?:[0-9]+))?$ the whole regex is eaten up by the greedy (.*).

Any idea how to deal with this problem in a good way?
BR
Patrik

Upvotes: 2

Views: 113

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

You can use

^(.*?)(?:(:)([0-9]*))?$

See the regex demo.

Details

  • ^ - start of string
  • (.*?) - Group 1: any zero or more chars other than line break chars, as few as possible
  • (?:(:)([0-9]*))? - an optional sequence of
    • (:) - Group 2: a colon
    • ([0-9]*) - Group 3: zero or more digits
  • $ - end of string.

Upvotes: 1

Related Questions