在许多编程语言中,可以使用正则表达式来实现捕获但不消耗字符串中的字符。以下是几种常见的编程语言的示例代码:
Python:
import re
str = "abc123"
pattern = r'(?=(\d))'
matches = re.findall(pattern, str)
for match in matches:
print(match)
Java:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "abc123";
String pattern = "(?=(\\d))";
Pattern regex = Pattern.compile(pattern);
Matcher matcher = regex.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
}
}
JavaScript:
const str = "abc123";
const pattern = /(?=(\d))/g;
const matches = str.match(pattern);
for (const match of matches) {
console.log(match);
}
这些代码示例中的正则表达式 (?=(\d))
使用了正向预查 (?!...)
,它表示后面必须紧接着指定的内容。在这里,我们预查了一个数字 \d
,以便在字符串中捕获数字字符,但不消耗它。然后,我们使用循环逐个处理匹配的结果。