How Match a Pattern in Text using Scanner and Pattern Classes?

烈酒焚心 提交于 2019-12-07 01:35:24

问题


i want to find whether a particular pattern exists in my text file or not.

i m using following classes for this :

java.util.regex.Pattern and java.util.Scanner;

my sample text Line is

String Line="DBREF  1A1F A  102   190  UNP    P08046   EGR1_MOUSE     308    396";

and, i want to match following kind of pattern :

A    102   190

where, at A's position a-z or A-Z but single charter.

at 102's position any integer and of any length.

at 190's position any integer and of any length.

and,My code for pattern matching is:

     Scanner sr=new Scanner(Line);
     Pattern p = Pattern.compile("\\s+([a-zA-Z]){1}\\s+\\d{1,}\\s+\\d{1,}\\s+");
     while(sr.hasNext(p))
     {
         System.out.println("Pattern exists");
         System.out.println("Matched String : "+sr.next(p));
     }

but, pattern is not matching even it exist there..

i think the problem is with my pattern string :

\\s+([a-zA-Z]){1}\\s+\\d{1,}\\s+\\d{1,}\\s+"

anybody, Plz help me what pattern string should i use????


回答1:


I'm not sure that Scanner is the best tool for this as hasNext(Pattern) checks to see if the next complete token has the next pattern. Your pattern goes across tokens.

Have you tried using a Matcher object instead of the Scanner?

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

public class Foo2 {
    public static void main(String[] args) {
        String line = "DBREF  1A1F A  102    190  UNP     P08046    EGR1_MOUSE      308     396";
        Pattern p = Pattern.compile("\\s+[a-zA-Z]\\s+\\d{1,}\\s+\\d{1,}\\s+");

        Matcher matcher = p.matcher(line);

        while (matcher.find()) {
            System.out.printf("group: %s%n", matcher.group());
        }
        System.out.println("done");
    }
}



回答2:


This regex line works:

\\s+\\w\\s+\\d+\\s+\\d+

group(0) of your matcher (p.matcher) gives A 102 190

.

[EDIT] Ok, I'll give you a complete working sample then:

    Pattern p = Pattern.compile("\\s+\\w\\s+\\d+\\s+\\d+");
    Matcher matcher = p.matcher("DBREF  1A1F A  102   190  UNP    P08046   EGR1_MOUSE     308    396");
    matcher.find();
    System.out.println("Found match: " + matcher.group(0));
    // Found match:  A 102 190


来源:https://stackoverflow.com/questions/4915967/how-match-a-pattern-in-text-using-scanner-and-pattern-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!