itrytowork09
itrytowork09

Reputation: 3

extract the last 2 fields regardless of size

I have been trying to get the last "two fields" of the following strings:

cc-api-data.bar.bar
external-atl3-1.xx.fbcdn.net
fbcdn.net

for the first 2 strings, I would like to only get the "bar.bar" and "fbcdn.net." However, for the last string, I want it to match the whole thing since it has all i want.

I am pretty confident i could do this in a simple script but I am trying to use regex in this case. I can only get the last part of the string on the last string but not the whole thing. And I cannot tell the regex which field to take. I literally just want the last two fields, no matter how many delimiters there are.

Any suggestions or is it even possible

Upvotes: 0

Views: 75

Answers (1)

Emma
Emma

Reputation: 27723

My guess is that we might want an expression that would have a $ anchor similar to:

([^.]*)\.([^.]*)$

towards the right side of our strings.

Please see the demo for additional explanation

I was wondering how does regex know to get only the part before the last period. Is it because it grabs any character thats not a "." and because it is at the end of the line? why couldnt it grab the first octet?

Good question, also a bit difficult to explain, by playing this demo, we can watch the many steps prior to getting to our matches:

Steps of Regular Expression

It would start char by char and test it against our expression, it would pass for our rules in the expression, yet in early chars or octet, once it would hit the $ end anchor, those early chars or octet would fail, because our last end of string rule has been broken.

Upvotes: 2

Related Questions