【问题标题】:Regex pattern error on API 21(android 5) and belowAPI 21(android 5)及以下版本的正则表达式模式错误
【发布时间】:2019-02-25 07:18:02
【问题描述】:

Android 5 及更低版本在运行时从我的正则表达式模式中获取错误:

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

这里是代码示例:

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())

这种模式在 21 岁以上的所有 API 上都非常有效。

【问题讨论】:

标签: java android regex kotlin android-5.0-lollipop


【解决方案1】:

似乎早期版本不支持命名组。根据此来源,named groups were introduced in Kotlin 1.2。如果您不需要这些子匹配项,请删除它们并仅使用正则表达式进行验证。

您的正则表达式非常低效,因为它包含许多嵌套的量化组。请参阅下面的“更清洁”版本。

此外,您似乎想检查输入字符串中是否存在正则表达式匹配。使用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

请参阅 Kotlin demoregex demo

如果你需要检查整个字符串匹配使用matches:

Regex(urlRegex).matches(sampleUrl)

another Kotlin demo

请注意,要定义正则表达式,您需要使用Regex 类构造函数。

【讨论】:

  • 问题是当它想要编译正则表达式模式时,它会在 api 21 及更低版本上抛出 PatternSyntaxException。我使用 java Pattern 类或 kotlin Regex 类都没有关系,它会抛出相同的异常。
  • @Alireza 您的模式不是很理想,请参阅答案中的更新模式。
  • @Alireza 是否支持命名组?你需要它们吗?从模式中删除所有?&lt;...&gt;s(?&lt;g1&gt;?&lt;g2&gt;?&lt;g3&gt;?&lt;TLD&gt;)。
  • @Alireza 不,这不好,一旦有人使用the string like here,您的应用程序就会崩溃(如果您将matches 与您的模式一起使用,我认为使用find 来验证没有意义) .
  • @a2hur 谢谢你的人,我删除了你提到的组,它起作用了。
猜你喜欢
  • 1970-01-01
  • 2018-11-23
  • 2012-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多