0

I am trying to fetch the IP addr and Port no separately from a given string.

STRING: 
(10.10.2.5:1567)

I need the O/P as

10.10.2.5
1567

I am new to RegEx and the pattern I am using is

\(([\d.]+):\d+\).*

This one seems to pick 10.10.2.5 but fails to pick the 1567

Matteo
  • 14,696
  • 9
  • 68
  • 106

3 Answers3

0

Use this regular expression:

\(([\d.]+):(\d+)\).*

Its is essentially the same regex as yours with the following 2 changes:

  1. Escape the parenthesis "(" and ").
  2. Add second capture group to get the port number.

So $1 will have the IP address and $2 will have the port number.

Aziz Shaikh
  • 16,245
  • 11
  • 62
  • 79
0

You can use this pattern

\d+[.]\d+[.]\d+[.]\d+(:\d+)?
Anirudha
  • 32,393
  • 7
  • 68
  • 89
0

You are capturing IP address with the first group

([\d.]+)

but not the port. You need another pair of parenthesis to define the second group

\(([\d.]+):([\d]+)\).*

Notice that the first group is also too generic: it will accept any mix of digits and dots:

23424....2342423

See Regular expression to match DNS hostname or IP Address? for a more strict expression

Community
  • 1
  • 1
Matteo
  • 14,696
  • 9
  • 68
  • 106