如何使用正则表达式找到字符串中模式的所有匹配 [英] How to find all matches of a pattern in a string using regex

查看:115
本文介绍了如何使用正则表达式找到字符串中模式的所有匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字符串:

  s =这是一个简单的字符串234这里还有其他的东西4334 

以及正则表达式:

<$ p $ regex =〜[0-9] {3}

如何从字符串中使用该正则表达式提取所有单词?在这种情况下, 234 433

解决方案

您可以使用 CharSequence.findAll

  def triads = s.findAll([0-9] {3})

assert triad == ['234' ,'433']

CharSequence.findAll


If I have a string like:

s = "This is a simple string 234 something else here as well 4334

and a regular expression like:

regex = ~"[0-9]{3}"

How can I extract all the words from the string using that regex? In this case 234 and 433?

解决方案

You can use CharSequence.findAll:

def triads = s.findAll("[0-9]{3}")

assert triads == ['234', '433']

Latest documentation of CharSequence.findAll

这篇关于如何使用正则表达式找到字符串中模式的所有匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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