Rename Pattern to Regex.

toRegex now converts string to our regex, and toPattern converts to JVM Pattern.
This commit is contained in:
Ilya Gorbunov
2015-04-09 16:16:52 +03:00
parent a4784dfa78
commit 559c1604d7
13 changed files with 52 additions and 50 deletions
@@ -19,19 +19,19 @@ package kotlin.text
private val TODO: Nothing get() = throw java.lang.UnsupportedOperationException() private val TODO: Nothing get() = throw java.lang.UnsupportedOperationException()
public enum class PatternOption(val value: String) { public enum class RegexOption(val value: String) {
IGNORE_CASE : PatternOption("i") IGNORE_CASE : RegexOption("i")
MULTILINE : PatternOption("m") MULTILINE : RegexOption("m")
} }
public data class MatchGroup(val value: String) public data class MatchGroup(val value: String)
public class Pattern (pattern: String, options: Set<PatternOption>) { public class Regex(pattern: String, options: Set<RegexOption>) {
public val pattern: String = pattern public val pattern: String = pattern
public val options: Set<PatternOption> = options.toSet() public val options: Set<RegexOption> = options.toSet()
private val nativePattern: RegExp = RegExp(pattern, options.map { it.value }.joinToString() + "g") private val nativePattern: RegExp = RegExp(pattern, options.map { it.value }.joinToString() + "g")
@@ -52,13 +52,13 @@ public class Pattern (pattern: String, options: Set<PatternOption>) {
public override fun toString(): String = nativePattern.toString() public override fun toString(): String = nativePattern.toString()
companion object { companion object {
public fun fromLiteral(literal: String): Pattern = Pattern(escape(literal)) public fun fromLiteral(literal: String): Regex = Regex(escape(literal))
public fun escape(literal: String): String = TODO public fun escape(literal: String): String = TODO
public fun escapeReplacement(literal: String): String = literal.nativeReplace(RegExp("\\$", "g"), "$$$$") public fun escapeReplacement(literal: String): String = literal.nativeReplace(RegExp("\\$", "g"), "$$$$")
} }
} }
public fun Pattern(pattern: String, vararg options: PatternOption): Pattern = Pattern(pattern, options.toSet()) public fun Regex(pattern: String, vararg options: RegexOption): Regex = Regex(pattern, options.toSet())
private fun RegExp.findNext(input: String, from: Int): MatchResult? { private fun RegExp.findNext(input: String, from: Int): MatchResult? {
+4 -4
View File
@@ -19,19 +19,19 @@ public fun String.nativeStartsWith(s: String, position: Int): Boolean = noImpl
native("endsWith") native("endsWith")
public fun String.nativeEndsWith(s: String): Boolean = noImpl public fun String.nativeEndsWith(s: String): Boolean = noImpl
deprecated("Use split(Pattern) instead.") deprecated("Use split(Regex) instead.")
library("splitString") library("splitString")
public fun String.splitWithRegex(regex: String): Array<String> = noImpl public fun String.splitWithRegex(regex: String): Array<String> = noImpl
deprecated("Use split(Pattern) instead.") deprecated("Use split(Regex) instead.")
library("splitString") library("splitString")
public fun String.splitWithRegex(regex: String, limit: Int): Array<String> = noImpl public fun String.splitWithRegex(regex: String, limit: Int): Array<String> = noImpl
deprecated("Use split(Pattern) instead.") deprecated("Use split(Regex) instead.")
library("splitString") library("splitString")
public fun String.split(regex: String): Array<String> = noImpl public fun String.split(regex: String): Array<String> = noImpl
deprecated("Use split(Pattern) instead.") deprecated("Use split(Regex) instead.")
library("splitString") library("splitString")
public fun String.split(regex: String, limit: Int): Array<String> = noImpl public fun String.split(regex: String, limit: Int): Array<String> = noImpl
+2 -2
View File
@@ -81,7 +81,7 @@ public inline fun String.decapitalize(): String {
public fun String.replace(oldValue: String, newValue: String): String = public fun String.replace(oldValue: String, newValue: String): String =
nativeReplace(RegExp(kotlin.text.Pattern.escape(oldValue),"g"), kotlin.text.Pattern.escapeReplacement(newValue)) nativeReplace(RegExp(kotlin.text.Regex.escape(oldValue),"g"), kotlin.text.Regex.escapeReplacement(newValue))
public fun String.replace(oldChar: Char, newChar: Char): String = public fun String.replace(oldChar: Char, newChar: Char): String =
nativeReplace(RegExp(kotlin.text.Pattern.escape(oldChar.toString()),"g"), newChar.toString()) nativeReplace(RegExp(kotlin.text.Regex.escape(oldChar.toString()),"g"), newChar.toString())
+1 -1
View File
@@ -121,7 +121,7 @@ public fun Node.previousElements(): List<Element> = previousSiblings().filterIsI
public var Element.classSet: MutableSet<String> public var Element.classSet: MutableSet<String>
get() { get() {
val answer = LinkedHashSet<String>() val answer = LinkedHashSet<String>()
val array = this.classes.split("""\s""".toRegex()) val array = this.classes.split("""\s""".toPattern())
for (s in array) { for (s in array) {
if (s.length() > 0) { if (s.length() > 0) {
answer.add(s) answer.add(s)
@@ -95,7 +95,7 @@ public fun File.filePathComponents(): FilePathComponents {
// Split not only by / or \, but also by //, ///, \\, \\\, etc. // Split not only by / or \, but also by //, ///, \\, \\\, etc.
val list = if (rootName.length() > 0 && subPath.isEmpty()) listOf() else val list = if (rootName.length() > 0 && subPath.isEmpty()) listOf() else
// Looks awful but we split just by /+ or \+ depending on OS // Looks awful but we split just by /+ or \+ depending on OS
subPath.split("""\Q${File.separatorChar}\E+""".toRegex()).toList().map { it -> File(it) } subPath.split("""\Q${File.separatorChar}\E+""".toPattern()).toList().map { it -> File(it) }
return FilePathComponents(rootName, list) return FilePathComponents(rootName, list)
} }
+2 -2
View File
@@ -1,7 +1,7 @@
package kotlin package kotlin
import java.util.NoSuchElementException import java.util.NoSuchElementException
import kotlin.text.Pattern import kotlin.text.Regex
/** Returns the string with leading and trailing text matching the given string removed */ /** Returns the string with leading and trailing text matching the given string removed */
deprecated("Use removeSurrounding(text, text) or removePrefix(text).removeSuffix(text)") deprecated("Use removeSurrounding(text, text) or removePrefix(text).removeSuffix(text)")
@@ -910,7 +910,7 @@ public fun String.split(vararg delimiters: Char, ignoreCase: Boolean = false, li
/** /**
* Splits this string around matches of the given regular expression. * Splits this string around matches of the given regular expression.
*/ */
public fun String.split(pattern: Pattern, limit: Int = 0): List<String> = pattern.split(this, limit) public fun String.split(pattern: Regex, limit: Int = 0): List<String> = pattern.split(this, limit)
/** /**
* Splits this string to a sequence of lines delimited by any of the following character sequences: CRLF, LF or CR. * Splits this string to a sequence of lines delimited by any of the following character sequences: CRLF, LF or CR.
@@ -94,7 +94,7 @@ public fun String.split(regex: Pattern, limit: Int = 0): List<String> = regex.sp
* Splits this string around matches of the given regular expression. * Splits this string around matches of the given regular expression.
*/ */
deprecated("Convert an argument to regex with toRegex or use splitBy instead.") deprecated("Convert an argument to regex with toRegex or use splitBy instead.")
public fun String.split(regex: String): Array<String> = split(regex.toRegex()).toTypedArray() public fun String.split(regex: String): Array<String> = split(regex.toPattern()).toTypedArray()
/** /**
@@ -403,7 +403,7 @@ public fun CharSequence.slice(range: IntRange): CharSequence {
* with the specified flags from [Pattern] or'd together * with the specified flags from [Pattern] or'd together
* so that strings can be split or matched on. * so that strings can be split or matched on.
*/ */
public fun String.toRegex(flags: Int = 0): java.util.regex.Pattern { public fun String.toPattern(flags: Int = 0): java.util.regex.Pattern {
return java.util.regex.Pattern.compile(this, flags) return java.util.regex.Pattern.compile(this, flags)
} }
@@ -480,7 +480,7 @@ public inline fun <T : Appendable> String.takeWhileTo(result: T, predicate: (Cha
*/ */
public fun String.replaceAll(regexp: String, body: (java.util.regex.MatchResult) -> String): String { public fun String.replaceAll(regexp: String, body: (java.util.regex.MatchResult) -> String): String {
val sb = StringBuilder(this.length()) val sb = StringBuilder(this.length())
val p = regexp.toRegex() val p = regexp.toPattern()
val m = p.matcher(this) val m = p.matcher(this)
var lastIdx = 0 var lastIdx = 0
@@ -30,7 +30,3 @@ public trait MatchResult {
public fun next(): MatchResult? public fun next(): MatchResult?
} }
// maybe move them to kotlin package to be more discoverable
public fun String.toPattern(vararg options: PatternOption): Pattern = Pattern(this, *options)
public fun String.toPattern(options: Set<PatternOption>): Pattern = Pattern(this, options)
@@ -0,0 +1,6 @@
package kotlin
import kotlin.text.*
public fun String.toRegex(vararg options: RegexOption): Regex = Regex(this, *options)
public fun String.toRegex(options: Set<RegexOption>): Regex = Regex(this, options)
@@ -16,7 +16,7 @@
package kotlin.text package kotlin.text
import java.util.regex.Pattern as NativePattern import java.util.regex.Pattern
import java.util.regex.Matcher import java.util.regex.Matcher
private val TODO: Nothing get() = throw UnsupportedOperationException() private val TODO: Nothing get() = throw UnsupportedOperationException()
@@ -31,32 +31,32 @@ public fun <T: FlagEnum> fromInt(value: Int, allValues: Array<T>): Set<T> =
allValues.filter({ value and it.mask == it.value }).toSet() allValues.filter({ value and it.mask == it.value }).toSet()
public enum class PatternOption(override val value: Int, override val mask: Int = value) : FlagEnum { public enum class RegexOption(override val value: Int, override val mask: Int = value) : FlagEnum {
// common // common
IGNORE_CASE : PatternOption(NativePattern.CASE_INSENSITIVE) IGNORE_CASE : RegexOption(Pattern.CASE_INSENSITIVE)
MULTILINE : PatternOption(NativePattern.MULTILINE) MULTILINE : RegexOption(Pattern.MULTILINE)
//jvm-specific //jvm-specific
LITERAL : PatternOption(NativePattern.LITERAL) LITERAL : RegexOption(Pattern.LITERAL)
UNICODE_CASE: PatternOption(NativePattern.UNICODE_CASE) UNICODE_CASE: RegexOption(Pattern.UNICODE_CASE)
UNIX_LINES: PatternOption(NativePattern.UNIX_LINES) UNIX_LINES: RegexOption(Pattern.UNIX_LINES)
COMMENTS: PatternOption(NativePattern.COMMENTS) COMMENTS: RegexOption(Pattern.COMMENTS)
DOT_MATCHES_ALL: PatternOption(NativePattern.DOTALL) DOT_MATCHES_ALL: RegexOption(Pattern.DOTALL)
CANON_EQ: PatternOption(NativePattern.CANON_EQ) CANON_EQ: RegexOption(Pattern.CANON_EQ)
} }
public data class MatchGroup(val value: String, val range: IntRange) public data class MatchGroup(val value: String, val range: IntRange)
public class Pattern ( /* visibility? */ val nativePattern: NativePattern) { public class Regex( /* visibility? */ val nativePattern: Pattern) {
public constructor(pattern: String, options: Set<PatternOption>): this(NativePattern.compile(pattern, options.toInt())) public constructor(pattern: String, options: Set<RegexOption>): this(Pattern.compile(pattern, options.toInt()))
public constructor(pattern: String, vararg options: PatternOption) : this(pattern, options.toSet()) public constructor(pattern: String, vararg options: RegexOption) : this(pattern, options.toSet())
public val pattern: String public val pattern: String
get() = nativePattern.pattern() get() = nativePattern.pattern()
public val options: Set<PatternOption> = fromInt(nativePattern.flags(), PatternOption.values()) public val options: Set<RegexOption> = fromInt(nativePattern.flags(), RegexOption.values())
public fun matches(input: CharSequence): Boolean = nativePattern.matcher(input).matches() public fun matches(input: CharSequence): Boolean = nativePattern.matcher(input).matches()
@@ -72,8 +72,8 @@ public class Pattern ( /* visibility? */ val nativePattern: NativePattern) {
public override fun toString(): String = nativePattern.toString() public override fun toString(): String = nativePattern.toString()
companion object { companion object {
public fun fromLiteral(literal: String): Pattern = Pattern(literal, PatternOption.LITERAL) public fun fromLiteral(literal: String): Regex = Regex(literal, RegexOption.LITERAL)
public fun escape(literal: String): String = NativePattern.quote(literal) public fun escape(literal: String): String = Pattern.quote(literal)
public fun escapeReplacement(literal: String): String = Matcher.quoteReplacement(literal) public fun escapeReplacement(literal: String): String = Matcher.quoteReplacement(literal)
} }
@@ -5,13 +5,13 @@ import kotlin.text.*
import org.junit.Test as test import org.junit.Test as test
class PatternJVMTest { class RegexJVMTest {
test fun matchGroups() { test fun matchGroups() {
val input = "1a 2b 3c" val input = "1a 2b 3c"
val pattern = "(\\d)(\\w)".toPattern() val regex = "(\\d)(\\w)".toRegex()
val matches = pattern.matchAll(input).toList() val matches = regex.matchAll(input).toList()
assertTrue(matches.all { it.groups.size() == 3 }) assertTrue(matches.all { it.groups.size() == 3 })
val m1 = matches[0] val m1 = matches[0]
assertEquals("1a", m1.groups[0]?.value) assertEquals("1a", m1.groups[0]?.value)
@@ -5,10 +5,10 @@ import kotlin.text.*
import kotlin.test.* import kotlin.test.*
import org.junit.Test as test import org.junit.Test as test
class PatternTest { class RegexTest {
test fun matchResult() { test fun matchResult() {
val p = "\\d+".toPattern() val p = "\\d+".toRegex()
val input = "123 456 789" val input = "123 456 789"
val first = p.match(input) val first = p.match(input)
@@ -30,7 +30,7 @@ class PatternTest {
test fun matchSequence() { test fun matchSequence() {
val input = "123 456 789" val input = "123 456 789"
val pattern = "\\d+".toPattern() val pattern = "\\d+".toRegex()
val matches = pattern.matchAll(input) val matches = pattern.matchAll(input)
val values = matches.map { it.value } val values = matches.map { it.value }
@@ -43,7 +43,7 @@ class PatternTest {
test fun matchGroups() { test fun matchGroups() {
val input = "1a 2b 3c" val input = "1a 2b 3c"
val pattern = "(\\d)(\\w)".toPattern() val pattern = "(\\d)(\\w)".toRegex()
val matches = pattern.matchAll(input).toList() val matches = pattern.matchAll(input).toList()
assertTrue(matches.all { it.groups.size() == 3 }) assertTrue(matches.all { it.groups.size() == 3 })
@@ -58,7 +58,7 @@ class PatternTest {
} }
test fun matchOptionalGroup() { test fun matchOptionalGroup() {
val pattern = "(hi)|(bye)".toPattern(PatternOption.IGNORE_CASE) val pattern = "(hi)|(bye)".toRegex(RegexOption.IGNORE_CASE)
val m1 = pattern.match("Hi!")!! val m1 = pattern.match("Hi!")!!
assertEquals(3, m1.groups.size()) assertEquals(3, m1.groups.size())
+2 -2
View File
@@ -5,8 +5,8 @@ import kotlin.test.*
import org.junit.Test as test import org.junit.Test as test
class StringUtilTest() { class StringUtilTest() {
test fun toRegex() { test fun toPattern() {
val re = """foo""".toRegex() val re = """foo""".toPattern()
val list = re.split("hellofoobar").toList() val list = re.split("hellofoobar").toList()
assertEquals(listOf("hello", "bar"), list) assertEquals(listOf("hello", "bar"), list)
} }