正则表达式 - 在一行中只匹配一次单词 [英] regular expression - match word only once in line

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

问题描述

案例:

  1. 你好再见你好再见
  2. 你好再见你好你好再见

我想匹配第 1 行(只有 'hello' 一次!)不想匹配第 2 行(多次包含 'hello')

I want to match line 1 (only has 'hello' once!) DO NOT want to match line 2 (contains 'hello' more than once)

尝试使用负面的前瞻和后视……没有任何真正的成功..

Tried using negative look ahead look behind and what not... without any real success..

推荐答案

一个简单的选项是这样的(使用多行标志而不是点全部):

A simple option is this (using the multiline flag and not dot-all):

^(?!.*\bhello\b.*\bhello\b).*\bhello\b.*$

首先,检查你没有有两次你好",然后检查你至少有一次.
还有其他方法可以检查相同的东西,但我认为这个方法很简单.

First, check you don't have 'hello' twice, and then check you have it at least once.
There are other ways to check for the same thing, but I think this one is pretty simple.

当然,你可以对\bhello\b进行简单的匹配,并统计匹配的次数...

Of course, you can simple match for \bhello\b and count the number of matches...

这篇关于正则表达式 - 在一行中只匹配一次单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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