How to match a template in text using scanner classes and templates?

I want to find if a specific template exists in my text file or not.

im using the following classes for this:

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

my sample text is Line

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

and, I want to match the following type of template:

A    102   190

where in position A az or AZ, but a single charter.

in position 102 any integer and any length.

in position 190 any integer and any length.

and my code for pattern matching:

     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));
     }

Well, the picture does not correspond even if there is any ..

I think the problem is with my template line:

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

anyone plz help me which template line should i use ????

+5
source share
2 answers

, Scanner - , hasNext (Pattern) , . .

Matcher ?

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

:

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

group(0) matcher (p.matcher) A 102 190

.

[EDIT] , :

    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
+3

All Articles