I have a string of text that contains an IP address with hyphens and words. I want to extract the IP address from it using a regular expression that also converts the hyphens to periods.
So to clarify, can the IP address be extracted and the hyphens be replaced with periods purely with a regular expression without using the regex in some code such as Java or Python:
What I have
ip-10-179-50-22.corp.dept.org.uk
What I want
10.179.50.22
I'm thinking that I need to extract 4 groups based on numbers and concatenate them with periods, but I have no idea how to do this or if this is even possible with only regex?
What I've tried
(\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3})
This gives me back 10-179-50-22
but I don't know how to replace on the matching group.
EDIT
I edited the question to clarify that I was trying to find a solution to find and replace with only a regular expression.
In summary, it looks like you can't just use a regex, but the regex needs to used with some code to achieve this
CodePudding user response:
We don't know which language your using but a lot of them have a .replace() with which you could change - for . or event sub string with a bit of adjusting should work for your problem.
CodePudding user response:
See regex101 example.
Regex:
.*\b(\d{2,3})-(\d{2,3})-(\d{2,3})-(\d{2,3})\b.*
Substitution:
\1.\2.\3.\4
Result:
10.179.50.22
Note that I am just using the regex you provided to match the IP address part, rather than a more accurate regex that would match any valid IP address.
CodePudding user response:
If you are able to use the sed command, this regex would do the job. It uses 4 groups like you suggested.
sed -i 's/^ip-\([0-9]*\)-\([0-9]*\)-\([0-9]*\)-\([0-9]*\).*/\1.\2.\3.\4/g'
It replaces ip-10-179-50-22.corp.dept.org.uk
with 10.179.50.22
.
You can test it on https://sed.js.org.