I’m having trouble to write regex to validate and group the bellow:
- c1dev01 –> valid
- c1dev01:25 –> valid
- 192.168.2.3 –> valid
- 192.168.2.3:189 –> valid
- c1dev01: –> valid
- c1dev01:aa –> not valid
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I guess the validation of the correct range is best not done in regex, but in a separate step. However, regex is great to validate the string format and extract the port number in one go. For the format we can require at most one colon and only digits to the right of it (at most 5). This corresponds to the following pattern string:
Where ^ and $ anchor the pattern to the beginning and end of the string. If you use this pattern in Regex.Match(), you can find the host name in match.Groups[1].Value and the port number in match.Groups[2].Value, to check that it’s not more than 65535.
Of course, you can further restrict the allowed characters for the host.