Okay, given the requirement, the constraints, and the information provided to this point, here is an Automator workflow you can use as your starting point to be tailored to your actual needs.
The workflow is set as a service (/quick action … Apple still seem to mix their terminology on this), so should be installed as such. It is set to receive text - though it does not really do anything with it, except to replace it.
There are three parts to the automation. The first gets the front most page’s URL from Safari. The next gets all of the URLs from that page. The third is a script that strips down the links to only what you want.
cat | egrep "domain.com|domain2.com" | sed -E "s/https:\/\/www.domain.com\/serviceX\/reference\/(.*)\/.*/\1/g" | sed -E "s/https:\/\/www.domain2.com\/reference\/serviceY\///g"
cat takes the output of the previous step and passes it on to
egrep for processing.
`egrep filters out URLs for the domains you don’t want. If necessary, you could expand these matches out to be even more specific. You didn’t provide any actual examples pages to work with, so I simplified this part to make it a bit easier to explain.
egrep then passes on to the first of two
sed commands. The first searches for the first format of URL and extracts the part you want using a regular expression pattern matched substitution. This output is then passed to the second
sed command, which does the same for the second format of URL.
The result of the second
sed is output by the service to replace the selected text.
If you are unfamiliar with
egrep, there are hundred if not thousands of articles, tutorials and man pages just a search engine’s use away, though it is useful to know that
egrep is effectively an enforcement of
Episode 34 is about regular expressions if you need to dive into those for the first time, and again there are many tutorials online and lots of useful references in this forum if you search for them.
With the above in place, if I select a suitable sample page (like this one I created with four links matching your formats and another that does not) in Safari, and highlight some text in TextEdit and select the example service provided above …
… I get an Automation pop-up, which I OK …
… and then the parts of the links you described as being required are output into TextEdit.
You could assign this a keyboard shortcut and then just trigger it in TextEdit to automatically insert the links you want from Safari.
There are many other ways you could tailor the automation too, but as noted above, the intention is to give you a viable starting point you can tailor to your needs.
Once you have modified the Automator workflow/service/quick action to work with the actual URLs you want to work with (rather than
serviceY you should be good to go.
Hopefully, everything is now laid out for you so that with just a small amount of effort you should be able to amend what has been provided to your needs as set out in your post(s).