正则表达式模式:以 X 开头,包含 Y,以 Z 结尾?
我有一个我制作的应用程序的配置文件,要加载配置,我需要首先从配置文件中解析它们。我有点卡住了。
这是配置文件的片段:
#0_downloaded_url:[http://example.com/to/be/downloaded/, 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/
我想匹配所有匹配的内容:#(digit)_(text and underscores):(anything)(linebreak),所以基本上一次一行。我还想对结果进行分组,因此我得到第一个数字,然后是数字后面的文本,最后是分号后面的文本(在本例中是 url)。
这是我到目前为止所想出的:
^#\d_\w*:.*
但这不是我想要的。它只匹配一行,并且不对结果进行分组。
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/, 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要将结果分组,您需要使用括号:(
注意,我使用了
+
但*
也可以,区别在于+
至少需要一个字符,但*
不会匹配任何字符)。至于匹配每一行,这也符合预期。根据您使用的语言,通常有一些方法可以在整个输入字符串中重复搜索并返回所有匹配项。
根据您使用的正则表达式引擎,您也许还可以为组分配名称。如果是这样,你可以这样做
To group the results you need to use parentheses:
(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