如何使用扫描仪和模式类匹配文本中的模式? [英] How Match a Pattern in Text using Scanner and Pattern Classes?

查看:182
本文介绍了如何使用扫描仪和模式类匹配文本中的模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查找我的文本文件中是否存在特定模式。

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

我正在使用以下类:

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

我的示例文本行是

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

其中,在A的位置az或AZ但是单个包机。

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

在102的位置任意整数和任何长度。

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

在190年代定位任何整数和任何长度。

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

任何人,Plz帮助我应该使用什么模式字符串????

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

推荐答案

我不确定Scanner是最好的工具,因为hasNext(模式)检查是否有下一个完整令牌有下一个模式。你的模式遍历标记。

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.

您是否尝试使用Matcher对象而不是扫描程序?

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

这篇关于如何使用扫描仪和模式类匹配文本中的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆