如何使用 java 模式匹配器解析 'P' 之后的所有内容?

how to parse everything that comes after 'P' with java pattern matcher?

我有一些以下形式的数据项:

blahblahblahP26
blahblahblahP82982
blahblahblahP0
blahblahblahP913

我知道 java 模式匹配器与普通正则表达式有点不同。

我想做的就是抓住P后面的所有东西。不多也不少。

怎么做?

您不需要正则表达式。尝试使用 substring

  String afterP= str.substring(str.indexOf('P')+1); 
         // Add 1 if don't want to include P

如果 P 出现多次而不是你可以使用 lastIndexOf('P')

我会清除你 P 之前的所有内容。有了这个,您还可以处理最后一个之前的可能 P

String afterP = str.replaceAll("^.*P", "");
    Pattern p=Pattern.compile("P[0-9]+");
    Matcher m=p.matcher(inp);
    while(m.find()){
        System.out.println(inp.substring(m.start(), m.end()));
    }

在 inp 中使用此正则表达式传递要解析的字符串。它适用于变量整数后跟 P

听起来你学过其他语言的正则表达式,那么this should be enough for you to learn about java regex . If you are new to regex , this tutorial就很详细了。 对于您的情况,这应该有效:

    Pattern pattern = Pattern.compile(".*?(P.*)"); // question mark is Reluctant quantifiers , it fetch sequence as short as possible. 
    Matcher matcher = pattern.matcher("blahblahblahP26");
    if(matcher.matches()){
        System.out.println(matcher.group(1));
    }