0

I am trying to create a regex that will return true only when the string only contains an anchor like so <a href="www.something.com">Link</a>.

Currently I have the following regex which almost works (?=.*^<a)(?=.*<\/a>).*/g

This works for the following scenarios:

<a href="www.something.com">Link</a> - Matches successfully

words before <a href="www.something.com">Link</a> - No matches - success

<a href="www.something.com">Link</a> words after - finds match - Not successful :(

I think I'm pretty close, I just need to know how to not find a match if there are any characters after the </a>.

7
  • Use $ to match the end of the string after </a> Commented Jan 30, 2020 at 18:03
  • 1
    What if it contains two anchors, like <a ...>foo</a>something else<a ...>bar</a> Commented Jan 30, 2020 at 18:04
  • ^ = beginning of string "^<" = starts with "<", $ = end of string ">$" = ends with ">" Commented Jan 30, 2020 at 18:04
  • Also, consider this: stackoverflow.com/a/1732454/3930247 Commented Jan 30, 2020 at 18:05
  • There's no need to use the g modifier if you're using a regexp for testing, rather than returning the matching part of a string or replacing. Commented Jan 30, 2020 at 18:06

1 Answer 1

1

Add a $ after the last >

(?=.*^<a)(?=.*<\/a>$).*

regex101

Alternatively, this regex matches links and discards everything else, irregardless of whether there are one or more links in the same line.

<a.*?\/a>

Sign up to request clarification or add additional context in comments.

1 Comment

Amazing, thanks for this! I was very close, just hadn't put the last character after the angle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.