[英]Regex Match Multi-line
我正在編寫一個小的bash腳本來編輯我的mkdocs配置文件並根據另一個目錄的內容更新它的一部分。
我試圖替換配置文件中的內容,但是在匹配需要用正則表達式模式替換的部分時遇到了一些麻煩。
這是我要更新的部分:
# Pages
pages:
- Home: index.md
- Getting Started:
- Installation: getting-started/installation.md
- Methods:
- config: methods/config.md
- add_header: methods/add_header.md
- add_tabs: methods/add_tabs.md
- add_fields: methods/add_fields.md
- footer: methods/footer.md
- Settings Fields:
- Text: fields/text.md
- Checkbox: fields/checkbox.md
- Radio: fields/radio.md
- Select: fields/select.md
- Image: fields/image.md
- Multicheck: fields/multicheck.md
- Hooks & Filters:
- Overview: actions/overview.md
- Examples:
- Basic Plugin: examples/basic-plugin.md
- Plugin Add-On: examples/plugin-addon.md
我要更新的部分是“設置字段”部分。
目前,我有:
/ {2}- Settings Fields:([^#]+) {2}-/g
這似乎符合我的需求,然后再匹配一些。
例如:
- Text: fields/text.md
- Checkbox: fields/checkbox.md
- Radio: fields/radio.md
- Select: fields/select.md
- Image: fields/image.md
- Multicheck: fields/multicheck.md
- Hooks & Filters:
- Overview: actions/overview.md
- Examples:
- Basic Plugin: examples/basic-plugin.md
-
理想情況下,我只想返回以下內容,因此我可以將其刪除並用新內容替換:
- Text: fields/text.md
- Checkbox: fields/checkbox.md
- Radio: fields/radio.md
- Select: fields/select.md
- Image: fields/image.md
- Multicheck: fields/multicheck.md
我已經設置了一個regex101測試,我在這里進行測試,但是我不是regex向導。 任何指針將不勝感激。
Regex101: https ://regex101.com/r/DViAoA/1
您可以修改正則表達式以使用不貪心的運算符,並為{2}
模式添加行首,如下所示:
{2}- Settings Fields:([^#]+?)^ {2}-
ungreedy ---^ ^--- start of line
您無需為此使用復雜的正則表達式。
您只需要Settings
和Hooks
之間的內容即可。
編輯以使其更靈活地使用模式。 現在它將匹配到2個空格和-或字符串結尾。
$re ='/\s{2}-\sHooks & Filters:(.*?)^\s{2}-|\z/ms';
$str = '# Pages
pages:
- Home: index.md
- Getting Started:
- Installation: getting-started/installation.md
- Methods:
- config: methods/config.md
- add_header: methods/add_header.md
- add_tabs: methods/add_tabs.md
- add_fields: methods/add_fields.md
- footer: methods/footer.md
- Settings Fields:
- Text: fields/text.md
- Checkbox: fields/checkbox.md
- Radio: fields/radio.md
- Select: fields/select.md
- Image: fields/image.md
- Multicheck: fields/multicheck.md
- Hooks & Filters:
- Overview: actions/overview.md
- Examples:
- Basic Plugin: examples/basic-plugin.md
- Plugin Add-On: examples/plugin-addon.md';
preg_match($re, $str, $matches);
Echo rtrim($matches[1]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.