开发者

Regex Pattern: Start with X, contain Y, end with Z?

I have a configuration file for an application I've made, and to load the configurations I need to parse them from the config file first. I'm kind of stuck.

Here is a snippet of the config file:

#0_downloaded_url:[http://example.com/to/be/downloaded/,开发者_StackOverflow http://example.com/to/be/downloaded/]
#0_follow_url:http://example.com/to/be/downloaded/
#0_download_url:http://example.com/to/be/downloaded/
#0_main_url:http://example.com/to/be/downloaded/
#1_downloaded_url:[http://example.com/to/be/downloaded/, http://example.com/to/be/downloaded/]
#1_follow_url:http://example.com/to/be/downloaded/
#1_download_url: http://example.com/to/be/downloaded/
#1_main_url:http://example.com/

I want to match everything that matches: #(digit)_(text and underscores):(anything)(linebreak), so basically one line at a time. I also wanna group the results, so I get the first digit, then the text after the digit, and at last the text (in this case a url) after the semicolon.

This is what I've come up with so far:

^#\d_\w*:.*

But that isn't what I want. It only matches one row, and it doesn't group the results.


To group the results you need to use parentheses:

^#(\d)_(\w+):(.+)

(note, I used + but * is fine too, the difference is + requires at least one character but * will match none).

As for matching every line, that too is behaving as expected. Depending on the language you're working in, there's generally methods for repeating the search across the entire input string and handing back all matches.

Depending on the regex engine you're using, you might be able to assign names to the groups as well. If so, you can do it like this

^#(?<id>\d)_(?<field>\w+):(?<value>.+)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜