Home » Android » android – What is the different between String.toRegex() extension and Regex("pattern")-Exceptionshub

android – What is the different between String.toRegex() extension and Regex("pattern")-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I have investigated Kotlin documents but couldn’t find the sensible answer about my question. When I use String.toRegex() in Android 5, getting crash for namedGroups. But if I use Regex(Pattern) there are no problem. I shuffled documents but couldnt find sensible datas. What do you think about it? What is the difference for toRegex() and Regex(“pattern”). Thanks a lot.

Edit
I know it seems the same at the background. But you could investigate the detail of Regex classes.

toRegex extension use expect class at the background.

expect class Regex {
constructor(pattern: String)
constructor(pattern: String, option: RegexOption)
constructor(pattern: String, options: Set<RegexOption>)

val pattern: String
val options: Set<RegexOption>
...

}

but Regex(pattern) class use actual Regex class

public actual class Regex
@PublishedApi
internal constructor(private val nativePattern: Pattern) : Serializable {


/** Creates a regular expression from the specified [pattern] string and the default options.  */
public actual constructor(pattern: String) : this(Pattern.compile(pattern))

/** Creates a regular expression from the specified [pattern] string and the specified single [option].  */
public actual constructor(pattern: String, option: RegexOption) : this(Pattern.compile(pattern, ensureUnicodeCase(option.value)))
How to&Answers:

They are the same. You can check the source code here, where it is defined as:

public inline fun String.toRegex(): Regex = Regex(this)