首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Groovy -正则表达式的行为不符合其应有的方式

Groovy -正则表达式的行为不符合其应有的方式
EN

Stack Overflow用户
提问于 2016-06-15 00:09:54
回答 1查看 127关注 0票数 0

我想从HTML文件的一行中提取一个数字。我逐行阅读了文件,并希望使用正则表达式从有问题的行中获取数字。

我试过这样做:

代码语言:javascript
复制
def reportFileContents = new File("-path to file-").text
                reportFileContents.eachLine{ line -> 

                    def valueMatcher = /[n50 length] [*]([0-9]+)/
                    def matcher = (line =~ valueMatcher)

                }

但当我打印出我的'matcher‘时,我得到的结果如下:

代码语言:javascript
复制
java.util.regex.Matcher[pattern=[n50 length] [*]([0-9]+) region=0,22 lastmatch=]

我在这里做错了什么?

EN

回答 1

Stack Overflow用户

发布于 2016-06-15 02:52:47

我猜你是说你正在尝试匹配一个像[n50 length] [*]123这样的字符串?如果是这样,请参见下面的示例。

代码语言:javascript
复制
def textWithMatches = '''blah blah blah [n50 length] [*]123 blah blah blah
                        |nothing here
                        |something else [n50 length] [*]321 something else'''.stripMargin()

def textWithNoMatches = 'no matches here'

assert (textWithMatches =~ /\[n50 length\] \[\*\](\d+)/).collect { it[1] } == [123, 321]
assert (textWithNoMatches =~ /\[n50 length\] \[\*\](\d+)/).collect { it[1] } == []
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37817154

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档