1

Android 5 and below getting error from my regex pattern on runtime:

java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 4:
(?<g1>(http|ftp)(s)?://)?(?<g2>[\w-:@])+(?<TLD>\.[\w\-]+)+(:\d+)?((|\?)([\w\-._~:/?#\[\]@!$&'()*+,;=.%])*)*

Here is code sample:

val urlRegex = "(?<g1>(http|ftp)(s)?://)?(?<g2>[\\w-:@])+(?<TLD>\\.[\\w\\-]+)+(:\\d+)?((|\\?)([\\w\\-._~:/?#\\[\\]@!$&'()*+,;=.%])*)*"
val sampleUrl = "https://www.google.com"
val urlMatchers = Pattern.compile(urlRegex).matcher(sampleUrl)
assert(urlMatchers.find())

This pattern works really fine on all APIs above 21.

2
  • Not heard of a regex being API dependant! This is interesting. Have you tried using the kotlin library for this? kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-regex/… Commented Feb 25, 2019 at 7:32
  • Yes! but unfortunately i got the same error. @user8159708 Commented Feb 25, 2019 at 7:40

1 Answer 1

5

It seems the earlier versions do not support named groups. As per this source, the named groups were introduced in Kotlin 1.2. Remove them if you do not need those submatches and only use the regex for validation.

Your regex is very inefficient as it contains a lot of nested quantified groups. See a "cleaner" version of it below.

Also, it seems you want to check if there is a regex match inside your input string. Use Regex#containsMatchIn():

val urlRegex = "(?:(?:http|ftp)s?://)?[\\w:@.-]+\\.[\\w-]+(?::\\d+)?\\??[\\w.~:/?#\\[\\]@!$&'()*+,;=.%-]*"
val sampleUrl = "https://www.google.com"
val urlMatchers = Regex(urlRegex).containsMatchIn(sampleUrl)
println(urlMatchers) // => true

See the Kotlin demo and the regex demo.

If you need to check the whole string match use matches:

Regex(urlRegex).matches(sampleUrl)

See another Kotlin demo.

Note that to define a regex, you need to use the Regex class constructor.

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

9 Comments

The problem is when it want to compile the regex pattern it throws PatternSyntaxException on api 21 and below. It doesn't matter that i use java Pattern class or kotlin Regex class, it throws the same exception.
@Alireza Your pattern was not quite optimal, see updated pattern in the answer.
@Alireza Does it support named groups? Do you need them at all? Remove all ?<...>s from the pattern (?<g1>, ?<g2>, ?<g3>, ?<TLD>).
@Alireza No, it is not good and once someone uses the string like here, your app will crash (if you use matches with your pattern, I see no point using find to validate).
@a2hur Thank's man i removed the groups that you mentioned and it worked.
|

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.