用于查找子字符串“hello hello"的次数的正则表达式;出现在字符串“hello hello hello"中 [英] Regex for finding number of times substring "hello hello" occurs in string "hello hello hello"

查看:64
本文介绍了用于查找子字符串“hello hello"的次数的正则表达式;出现在字符串“hello hello hello"中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取字符串中子字符串出现的次数.

I want to get the count of occurrence of a substring within a string.

我的字符串是"hello hello hello".我想获得 "hello hello" 出现的次数,在上面的例子中是 2.
有人可以帮我找到一个正则表达式吗?

My string is "hello hello hello". I want to get the number of times "hello hello" occurs in it, which in the above case is 2.
Can someone please help me find a regex for it?

推荐答案

取决于您要计算 hello(在您的示例中为 3)或 hello 的出现次数你好(就是2),你可以这样做:

Depending on either you want to count the number of occurrence of hello (which is 3 in your example) or hello hello (wich is 2), you can do:

#!/usr/bin/perl 
use 5.10.1;
use warnings;
use strict;

my $str = q/hello hello hello/;
my $count1 =()= $str =~ /(?=\bhello hello\b)/g;
say $count1;  # gives 2

my $count2 =()= $str =~ /\bhello\b/g;
say $count2;  # gives 3

这篇关于用于查找子字符串“hello hello"的次数的正则表达式;出现在字符串“hello hello hello"中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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