java - Java 正则表达式字符串匹配
问题描述
我正在使用正则表达式匹配器进行近似字符串匹配。我有一个关于如何使其允许重叠匹配的问题。目前,它找到一个匹配项,然后跳到该匹配项的末尾并从那里开始搜索。
当前代码
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class BNDM2 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String nucleotides,pattern;
System.out.print("Enter sequence:");
pattern = sc.nextLine();
System.out.print("Enter nucleotides:");
nucleotides= sc.nextLine();
// first convert the pattern into a proper regex
// i.e. replacing any N with [ATCG]
Pattern regex = Pattern.compile(pattern.replaceAll("N", "[ATCG]"));
// create a Matcher to find everywhere that the pattern matches
Matcher m = regex.matcher(nucleotides);
// find all the matches
while (m.find()) {
System.out.println("Match found:");
System.out.println("start:" + m.start());
System.out.println("end:" + (m.end() - 1)); // minus 1 here because the end of a regex match is always off by 1
System.out.println();
System.out.println("|" + nucleotides.substring(m.start(),m.end())+"|......");
}
}
}
解决方案
您可以使用public boolean find(int start)
并循环遍历整个字符串
int index = 0;
while (index < nucleotides.length() && m.find(index)) {
//your code here
index=m.start()+1;
}
推荐阅读
- gdb - 从 spi 配置返回时,Arty-A7-100T 上 E310 上的 example-spi 卡住了
- javascript - Google Apps 脚本 Oauth1 / Trello API“无效签名”
- bazel - Jenkins(Linux,CentOS)上的 Bazel 本地 JDK 权限问题
- swiftui - ForEach 循环中单元格的屏幕截图
- python - python dotenv CLI 的正确文件规范?
- uwp - C++Winrt 如何从异步方法中抛出异常
- java - Java非贪婪(?)正则表达式匹配字符串
- snowflake-cloud-data-platform - 雪管 REST API 插入报告“文件”:[]
- jpa - JPA:使用fluent或@Query对OneToMany关系的子表进行连接和排序/限制约束
- google-analytics - 无法使用 Google Analytics 设置 Matillion OAuth