0

I'm trying to write a regular expression in an Apache Velocity template to check if a string contains a URL.

My code is below. The variable $quoteValue is currently set to contain the string "This is a pullquote test: http://www.google.com"

##Set the regular expression to be used to find a URL
            #set($urlRegex = '(.*)(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?(.*)')
            Is there a match? $quoteValue.matches($urlRegex)

However, the $quoteValue.matches($urlRegex) method always returns false, when I would expect it to return true in this case. How can I get it to recognise that the string contains a URL? I'm assuming this is something to do with escaping special characters.

Victoria
  • 901
  • 3
  • 15
  • 30
  • Most probably the backslashes must be doubled. The [regex seems to work](https://regex101.com/r/bS6sU3/1). – Wiktor Stribiżew Apr 20 '16 at 11:54
  • Thanks - I've just tried doubling the backslashes, but it's still returning false. – Victoria Apr 20 '16 at 11:57
  • I see, you are using single quotes around the pattern, really, doubling the backslashes is not necessary. If there are no newline symbols, `.*` should match. If not, you need to add `(?s)` at the pattern start. Also, try with a very simple regex like `(?s).*http.*` - if it fails, the problem is not with a regex at all, but how you are using it. – Wiktor Stribiżew Apr 20 '16 at 12:01
  • Adding (?s) to the start of the regular expression has made it work. Thanks for pointing me in the right direction! – Victoria Apr 20 '16 at 14:08

2 Answers2

2

.matches() is implicitly anchored with ^$

In other words, it only returns true when the entire thing matches.

Replace it with .find().

Laurel
  • 5,965
  • 14
  • 31
  • 57
0

I have managed to resolve this issue using the following code for the regular expression:

#set($urlRegex = '(?s).*(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?.*')

It was the (?s) at the start which made it work!

Victoria
  • 901
  • 3
  • 15
  • 30