Java字符串和正则表达式匹配

标签 java regex string

我想在另一个字符串中搜索一个字符串(由字符串和正则表达式连接而成)。如果第一个字符串出现在第二个字符串中,那么我想获取匹配短语的起始地址和结束地址。 在下面的代码中,我想在“baby_NN accessories_NNS India_NNP is_VBZ an_DT online_JJ shopping_NN portal_NN”中搜索“baby accessories India”,并希望得到“baby_NN accessories_NNS India_NNP”作为结果。

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatching {


public static void main(String aaa[])throws IOException
{

        String line="baby accessories India";
        String []str=line.split("\\ ");

        String temp="";

        int i,j;
        j=0;

        String regEx1 = "([A-Z]+)[$]?";

        for(i=0;i<str.length;i++)
            temp=temp+str[i]+"_"+regEx1+" ";


        String para2="baby_NN accessories_NNS India_NNP is_VBZ an_DT online_JJ shopping_NN portal_NN ";
        Pattern pattern1 = Pattern.compile(temp);
        Matcher matcher1 = pattern1.matcher(para2);

        if (para2.matches(temp)) {
            i = matcher1.start();
            j = matcher1.end();
            String temp1=para2.substring(i,j);
            System.out.println(temp1);

        }
        else {
            System.out.println("Error");
        }

}
}

最佳答案

试试Matcher#find()

if (matcher1.find()) 

而不是 String#matches()匹配整个字符串,而不仅仅是它的一部分。

if (para2.matches(temp))

输出:

baby_NN accessories_NNS India_NNP  

还有一点变化

if (matcher1.find()) {
    i = matcher1.start();
    j = matcher1.end();
    String temp1 = para2.substring(i, j-1); // Use (j-1) to skip last space character
    System.out.println(temp1);
} 

关于Java字符串和正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24030551/

相关文章:

java - "Unresolved compilation pro..."异常错误

java - 读取java进程的输入流

java - Java 中的 "implements Runnable"与 "extends Thread"

c - C 中的字符串反转 : What is it I am doing wrong?

java - ByteArrayInputStream/ByteArrayOutputStream的实际使用

regex - 匹配除数字正则表达式之外的所有内容

python - 如何在 python 中使用内联正则表达式修饰符

javascript - 正则表达式查找不在两个其他字符之间出现的所有字符

java - String[] 或 ArrayList 更适合作为 HashMap 中的 Key?

c++ - 如何获取字符串输出的宽度?