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
572 views
in Technique[技术] by (71.8m points)

php - Capturing a pattern of unknown repitition in PCRE

This may be a quick question for experienced regular expressionists, but I'm having trouble getting my match to execute correctly.

Suppose I had a string that looked like this:

http://aaa-bbbb-cc-ddddd-eee-.sub.dom

I would like to go capture all of the "aaa", "bbbb", "cc", and "ddddd" substrings, but I'm not sure how many there will be (e.g., having all triplets up through "zzz").

This is the regular expression I'm trying to use right now:

/http://(w*?-)+.sub.dom/

I wrote it this way because:

  1. I want to match substrings, but I want each to terminate when a - is parsed
  2. I want to capture one or more of these substrings

But it seems to only be saving the last match that it makes (in the above case, it would only match "eee-".

Is there a good way to capture all of the matched substrings?

More information: I'm using PHP's PCRE function preg_replace_callback. Thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

No, it is not possible to match an unknown number of capture groups.

If you try to repeat a capture group, it will always contain the last value captured.

Could you explain a bit more broadly what you're trying to do? Perhaps there is another simple way to do it (possibly without regular expressions).


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

...