正则表达式(Regular Expression,简称Regex)是一种用于描述字符串模式的工具。它广泛应用于数据验证、文本解析、日志处理等场景。在Kotlin中,正则表达式的使用十分方便,为开发者提供了强大的字符串操作功能。 2. Kotlin中正则表达式的基本语法和常用模式 Kotlin中的正则表达式语法与Java相似,包括一些基本的元字符和预定义字符...
复制代码 提取子字符串:正则表达式可以帮助你从一个字符串中提取与模式匹配的子字符串。例如,你可以从一个文本中提取所有的电子邮件地址或电话号码。 val text = "Please contact us at support@example.com or call us at 123-456-7890." val emailPattern = Regex("\\b[A-Za-z0-9._%+-]+@[A-Za-z...
import java.io.IOException import java.util.regex.Pattern fun main() { val url = "http://www.example.com" val proxyHost = "ip.16yun.cn" val proxyPort = 31111 // 创建 HttpURLConnection 对象valconnection=URL(url).openConnection()asHttpURLConnection// 设置代理服务器connection.setProxy(proxy...
使用正则表达式可以轻松地在字符串中匹配和提取特定的模式。例如,你可以使用find()函数来查找字符串中是否包含某个子字符串,或者使用regexExtract()函数来提取与正则表达式匹配的所有子字符串。 val text = "The quick brown fox jumps over the lazy dog." val pattern = "fox" val match = text.find(pattern...
val pattern = "dog".toRegex(RegexOption.IGNORE_CASE) words.forEach { word -> if (pattern.matches(word)) { println("$word matches") } } } In the example, we apply the pattern on words regardless of the case. val pattern = "dog".toRegex(RegexOption.IGNORE_CASE) ...
import java.util.regex.Pattern fun main() { val url = "http://www.example.com" val proxyHost = "ip.16yun.cn" val proxyPort = 31111 // 创建 HttpURLConnection 对象 val connection = URL(url).openConnection() as HttpURLConnection ...
import java.util.regex.Pattern fun main() { val url = "http://www.example.com" val proxyHost = "ip.16yun.cn" val proxyPort = 31111 // 创建 HttpURLConnection 对象 val connection = URL(url).openConnection() as HttpURLConnection ...
fun main() { val hexNumberRegex = run { val digits = "0-9" val hexDigits = "A-Fa-f" val sign = "+-" Regex("[$sign]?[$digits$hexDigits]+") } for (match in hexNumberRegex.findAll("+1234 -FFFF not-a-number")) { println(match.value) } } apply context 对象可用作接收器...
"ab.cd12.ef"split(".") Kotlin里用Regex类表示正则,使用正则实现如下 val regex = Regex("\\.") val result = "ab.cd12.ef".split(regex.toPattern()) 解析字符串在Kotlin变得更容易了,除了split,Kotlin还提供了其他方法,再看一个例子 解析文件路径 解析一个文件路径:“/Users/mine/Documents/MyDocumen...
Regex("[$sign]?[$digits$hexDigits]+") } for (match in hexNumberRegex.findAll("+1234 -FFFF not-a-number")) { println(match.value) } apply 上下文对象 作为接收者( this )来访问。返回值 是上下文对象本身。 对于不返回值且主要在接收者(this)对象的成员上运行的代码块使用 apply。apply 的常...