Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

javascript - Regex match count of characters that are separated by non-matching characters

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

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.

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.

Any ideas on this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Hey I think this would a simple but working one:

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

Breaking the regex down:

  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. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...