groovy、java 正则中怎么提取单引号、双引号中的内容?但是必须要成对出现才匹配比如有字符串helloworld只能匹配到helloworld
在Groovy和Java中,可以使用正则表达式来提取单引号或双引号中的内容。下面是一个示例代码:
import java.util.regex.Matcher
import java.util.regex.Pattern
def extractContent(String input, String quoteType) {
Pattern pattern = Pattern.compile(quoteType + "(.*?)" + quoteType)
Matcher matcher = pattern.matcher(input)
if (matcher.find()) {
return matcher.group(1)
} else {
return null
}
}
String input = "hello'world'"
String quoteType = "'"
String content = extractContent(input, quoteType)
println(content)
在上述示例中,extractContent方法接收两个参数:输入字符串和引号类型。它使用正则表达式 quoteType + "(.*?)" + quoteType 来匹配成对出现的引号中的内容。
调用 extractContent 方法并传入输入字符串和引号类型后,将返回匹配到的内容。在示例中,输出为 hello'world'。
你可以根据需要修改引号类型或将该方法嵌入到你的代码中
原文地址: https://www.cveoy.top/t/topic/iqJK 著作权归作者所有。请勿转载和采集!