正则表达式在字符串中查找单词 [英] Regex find word in the string

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

问题描述

一般来说,我想在字符串中找到一些子字符串,但前提是它包含在那里.

In general terms I want to find in the string some substring but only if it is contained there.

我有表情:

^.*(\bpass\b)?.*$

和测试字符串:

high pass h3 

当我通过表达式测试字符串时,我看到找到了整个字符串(但没有找到组pass"):

When I test the string via expression I see that whole string is found (but group "pass" not):

match : true
groups count : 1  
group : high pass h3 

但我需要的是,这场比赛有 2 组:1:高通h32:通过

But that I needed, is that match has 2 groups : 1: high pass h3 2: pass

例如,当我测试字符串 - high h3 时,我仍然找到了 1 个组 - high h3

And when I test, for example, the string - high h3, I still had 1 group found - high h3

我该怎么做?

推荐答案

使用这个:

^(.*?(\bpass\b)[^$]*)$

  1. 第一次捕获整行.
  2. 第二次捕获预期词.

查看演示.

更多解释:

          ┌ first capture
          |
 ⧽------------------⧼
^(.*?(\bpass\b)[^$]*)$
  ⧽-⧼          ⧽---⧼
   | ⧽--------⧼  |
   |     |       └ all characters who are not the end of the string
   |     |
   |     └ second capture
   |
   └ optional begin characters

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

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