正则表达式匹配由不匹配字符分隔的字符数 [英] Regex match count of characters that are separated by non-matching characters

查看:116
本文介绍了正则表达式匹配由不匹配字符分隔的字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算字符数,但它们可能被不匹配的字符分隔。

I want to count characters, but they may be separated by characters that do not match.

这是一个例子。
我想匹配一个包含10个或更多单词字符的文本。它可能包含空格,但我不想计算空格。

Here is an example. I want to match a text that has 10 or more word-characters. It may include spaces but i don't want to count the spaces.

匹配:foo bar baz(应该算9) )

匹配:a           a(应计数2)

应该匹配:foo baz bars(应该算10,匹配整个字符串)

Should not match: "foo bar baz" (should count 9)
Should not match: "a          a" (should count 2)
Should match: "foo baz bars" (should count 10, match whole string)

这就是我提出来的,但它算的是整个事情:

This is what i came up with, but it counts the whole thing:

((?<=\s)*\w(?=\s)*){10}

编辑我不想包含空格来计算。对不起,我编辑了几次,我没有正确描述。

Edit I do not want to include spaces for counting. Sorry I edited this a few times, I didn't describe it correctly.

有什么想法吗?

推荐答案

嘿,我认为这是一个简单但有效的方法:

Hey I think this would a simple but working one:

( *?[0-9a-zA-Z] *?){10,}

打破正则表达式:


  1. (*?--------它可以以空格开头

  2. [0-9a-zA-Z] - 使用字母数字值

  3. *?)---------它可以以空格结尾

  4. {10,} -------匹配此模式10次或以上

  1. ( *? --------It can start with space(s)
  2. [0-9a-zA-Z] -Followed with the alphanumeric values
  3. *?) ---------It can end with space(s)
  4. {10,} -------Matches this pattern 10 or more times

键:当我查看正则表达式的计数时,它适用于该组,即括号中的内容(),这种情况下,多个空格跟随一个从字母数字值后跟空格仍然算作一个匹配。希望能帮助到你。 :)

Key: When I look at the count for regexes, it applies to the group, i.e., the things in the brackets "()", this case, multiple spaces followed ONE from the alphanumeric values followed by spaces are still counted as one match. Hope it helps. :)

这篇关于正则表达式匹配由不匹配字符分隔的字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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