如何从正则表达式的所有​​比赛? [英] How to get all matches from regex?

查看:167
本文介绍了如何从正则表达式的所有​​比赛?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得 [0-9A-Z] +?的所有实例进行处理后。
我有

I would like to get all occurrences of [0-9A-Z]+? for processing later. I do have

if [[ `cat file` =~ '[0-9A-Z]+?' ]]; then
  echo $BASH_REMATCH;
fi

这给了我的第一场比赛,但我怎么能处理文件中的所有比赛?

Which gives me first match, but how could I process all the matches in the file?

感谢您

推荐答案

如果你想获得只是一个普通的前pression的匹配的文本,我会用

If you want to get just the matched text of a regular expression, I would use

grep -o 'regex' file

在您的code的精神,我将修改它是

In the spirit of your code I would modify it to be

while read line; do
    [[ $line =~ regex ]] || continue
    # do somethinw with $line or $BASH_REMATCH, perhaps put it in an array.
done < file

如果你想在同一行匹配多个正则表达式,这里是一个办法。

If you want to match multiple regexes on the same line, here is a way.

while read line; do
    # do somethinw with $line
done < <(grep -o 'regex' file)

我假设你的正则表达式应该是一个什么样的真的做一个简单的例子。的?是不是有帮助,你的报价是匹配一个字符串。

I assume your regex is supposed to be a simplified example of what your really doing. The ? is not helpfull and your quotes are matching a literal string.

这篇关于如何从正则表达式的所有​​比赛?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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