【问题标题】:Java Regex String MatchingJava 正则表达式字符串匹配
【发布时间】:2018-11-13 23:25:46
【问题描述】:

我正在使用正则表达式匹配器进行近似字符串匹配。我有一个关于如何使其允许重叠匹配的问题。目前,它找到一个匹配项,然后跳到该匹配项的末尾并从那里开始搜索。

当前代码

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())+"|......");
    }
}

}

【问题讨论】:

  • 您能否向我们展示您的输入数据样本、您获得的结果以及它们与您的预期结果有何不同?
  • 您可能需要量词,但正如 mypetlion 所说,如果没有输入 + 当前输出与所需输出,很难帮助您...

标签: java regex


【解决方案1】:

您可以使用public boolean find(int start) 并遍历整个字符串

 int index = 0;

 while (index < nucleotides.length()  && m.find(index)) {
          //your code here
          index=m.start()+1;
 }

【讨论】:

    猜你喜欢
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 2013-12-25
    相关资源
    最近更新 更多