使用Python在同一字符串中多次执行re.match()

2024-05-16 09:10:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我要找到一个正则表达式:ABC:`hello`模式。这是密码。

format =r".*\:(.*)\:\`(.*)\`"
patt = re.compile(format, re.I|re.U)
m = patt.match(l.rstrip())
if m:
    ...

当模式在一行中出现一次时,它工作得很好,但有一个例子:tagbox:`Verilog`:tagbox:`Multiply`:tagbox:`VHDL`。它只找到最后一个。

我怎样才能找到这三种模式呢?

编辑

根据Paul Z的回答,我可以用这个代码

format = r"\:([^:]*)\:\`([^`]*)\`"
patt = re.compile(format, re.I|re.U)
for m in patt.finditer(l.rstrip()):
    tag, value = m.groups()  
    print tag, ":::", value

结果

tagbox ::: Verilog
tagbox ::: Multiply
tagbox ::: VHDL

Tags: reformat密码hellovaluetag模式verilog
3条回答

也许是因为name=in。next()和name=in。while循环中的nextLine()。我想一个就够了。 例如:

name=in。next()
做{
.....
....
name=in。next()
}而(名称!=“ENDDATA”)

问题似乎出在第french=in.nextInt()行。正如documentation所说,nextInt()将在没有更多的输入可读取时抛出NoSuchElementException

public int nextInt()

Throws:

NoSuchElementException - if input is exhausted

可能您在student.dat中的一个条目没有按您期望的方式填充

在。nextInt()正在抛出NoTouchElementException

您的文件似乎包含不正确的数据

您的while循环将永远不会中断,因为您的条件:

   while(name!="ENDDATA")

永远都是真的。这就是为什么当所有令牌都用完时,scanner对象抛出NosTouchElementException。由于异常,while循环之后的print语句不会执行

尝试使用scanner的hasNext()方法检查下一个令牌

用这个while替换while循环

  while (in.hasNext()){        //Sentinel condition
            count++;                    //Keeps count of students
            name = in.next();
            if(name.equals("ENDDATA")){
               break;
            }
            spanish=in.nextInt();
            math=in.nextInt();
            french=in.nextInt();
            english=in.nextInt();
            sum = spanish + math + french + english;
            avg = sum/4;                                    //Claculates Average
            System.out.printf("%s - %.0f\n",name,avg);

                if (avg > highAvg){                         //Checks for the highest Average
                    highAvg = avg;
                    highName = name;
                }
                if (spanish > highSpan){
                    highSpan = spanish;
                }
                if (math > highMath){
                    highMath = math;                        //Checks for the highest mark for each subject
                }
                if (french > highFren){
                    highFren = french;
                }
                if (english > highEng){
                    highEng = english;
                }


 }

学生。dat文件格式应如下所示:

Shelly 2 2 3 4
Brown 34 2 1 4
Pink 23 45 21 1
ENDDATA

相关问题 更多 >