I need to get the port from url, I use the following which works
https://regex101.com/r/yoBODY/1
(?:([^@]*)@)?(.\[. \]|([^:] ))(?:[:](\d ))?
As im quite new to regex, Am I missing something?
This is the inputs and from it I need to get the port
test:222
https://aaa.com:333
https://www.aaa.com:333
aaa.bbb.cccc:8000
im getting some URI/URL with port
if its OK please let me know
CodePudding user response:
For strings used as standalone strings you can use
^(?:https?:\/\/)?(?:([^@]*)@)?(\[[^][] \]|([^:] ))(?::(\d ))?$
If you match these strings as lines in a multiline text, it is advisable to add \n
and \r
to the negated character classes to avoid overflowing on next line(s):
^(?:https?:\/\/)?(?:([^@\r\n]*)@)?(\[[^][\r\n] \]|([^:\r\n] ))(?::(\d ))?$
See the regex demo. Details:
^
- start of string(?:https?:\/\/)?
- an optionalhttp://
orhttps://
(?:([^@]*)@)?
- an optional sequence of any zero or more chars other than@
(captured into Group 1) and then a@
char(\[[^][] \]|([^:] ))
- Group 2: either[
, one or more chars other than[
and]
and then]
or one or more chars other than:
captured into Group 3(?::(\d ))?
- an optional sequence of:
and one or more digits captured into Group 4$
- end of string.