在Dart中使用正则表达式匹配两个字符串间的所有子串
提取两个特定标识之间的所有子串
要从长字符串中提取所有位于Text('和'之间的子串,最直接的方法是使用正则表达式的非贪婪捕获,避免匹配范围过度延伸。以下是不同语言的实现示例:
Java 实现
import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ExtractSubstrings { public static void main(String[] args) { String s = "abcdText('hello')abcd efghText('world')"; String startMarker = "Text('"; String endMarker = "'"; // 转义标识中的特殊字符,避免正则语法冲突 String regex = Pattern.quote(startMarker) + "(.*?)" + Pattern.quote(endMarker); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(s); List<String> results = new ArrayList<>(); // 遍历所有匹配项,收集捕获的子串 while (matcher.find()) { results.add(matcher.group(1)); } System.out.println(results); // 输出: [hello, world] } }
Python 实现
import re s = "abcdText('hello')abcd efghText('world')" start_marker = "Text('" end_marker = "'" # 转义特殊字符,构建正则表达式 regex = re.escape(start_marker) + "(.*?)" + re.escape(end_marker) # 直接获取所有匹配的子串列表 results = re.findall(regex, s) print(results) # 输出: ['hello', 'world']
关键说明
Pattern.quote()(Java)或re.escape()(Python):用来转义标识中的特殊字符(比如(、'),防止它们被当作正则语法解析。(.*?):非贪婪捕获组,会匹配到最近的结束标识就停止,确保每个子串独立,不会把多个结果合并成一个。- 遍历匹配结果:通过循环(Java)或
findall(Python)收集所有符合条件的子串,最终得到目标列表。
内容的提问来源于stack exchange,提问作者VipiN Negi
相关产品推荐
相关产品推荐

