求助:正则匹配Example/Examples到指定引号间文本的问题
正则表达式匹配问题解决方案
需求
编写正则表达式,匹配单词Example(或Examples)之后的文本,提取从Example(s)之后到第一个Python代码块结束标记```之间的内容。
示例文本
"In this kata you are required to, given a string, replace every letter with its position in the alphabet. If anything in the text isn't a letter, ignore it and don't return it. `'a' = 1`, `'b' = 2`, etc. ## Example <!-- unlisted languages will use the first entry. please keep python up top. --> ```python alphabet_position('The sunset sets at twelve o' clock.') ``` ```crystal alphabet_position('The sunset sets at twelve o' clock.') ``` Should return `20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11` ( as a string )"
预期输出
<!-- unlisted languages will use the first entry. please keep python up top. --> ```python alphabet_position('The sunset sets at twelve o' clock.') ```
尝试的方案
const matched = test.match('Example(.)(.*)```(.*)```')
该正则未匹配到任何内容,返回空值。
解决方案
正确正则表达式
使用以下正则可以精准匹配目标内容:
// 支持ES2018+的s标志(.匹配换行) const regex = /Example(s)?\s*(.*?```python.*?```)/s; const matched = test.match(regex); // 兼容旧环境的写法(用[\s\S]替代.匹配所有字符) const regexCompat = /Example(s)?\s*([\s\S]*?```python[\s\S]*?```)/; const matchedCompat = test.match(regexCompat);
正则细节说明
Example(s)?:匹配Example或Examples,(s)?表示s为可选字符。\s*:匹配Example(s)之后的任意空白字符(包括空格、制表符、换行),避免因格式空格导致匹配失败。(.*?```python.*?```):.*?采用非贪婪匹配,确保只捕获到第一个Python代码块,不会误包含后面的Crystal代码;- ````python``````精准定位Python代码块的起止标记;
s标志让.可以匹配换行符,处理跨多行的注释和代码块内容。
提取结果
匹配成功后,matched[2](或matchedCompat[2])即为预期输出的目标内容。
内容的提问来源于stack exchange,提问作者Emm
相关产品推荐
相关产品推荐

