regex - 为什么我的正则表达式在在线正则表达式测试仪上运行时无法选择正确的元素
问题描述
我有许多 xml 文件,它们在 node 中嵌入了 HTML。我需要捕获所有不是标签的东西,在文本周围添加一些非 HTML 标签(用于moodle)。
我正在使用 bash 脚本从命令行处理文件。我正在使用 xpath 来获取内容,通过 xargs 管道偷偷地撕掉换行符,然后通过 sed 管道。
下面是一个标签示例:
xpath -q -e '/activity/page/content' page.xml|xargs
<content><h3 style=float:right><img
src=@@PLUGINFILE@@/consumables.png> </h3> <h3>TITLE</h3>
<p>In order to conduct an LE5 drug test you need a Druglizaer
(batch controlled) foil pouch that contains two items:</p>
<p></p> <ol> <li><span style=font-
weight:900>Druglizer Cartridge</span></li><li><span
style=font-weight:900>Druglizer Oral Fluid
Collector</span></li> </ol> <p></p></content>
在https://regex101.com/上,我使用\>(.*?)\<
了按预期对文本进行分组。但是当我使用 sed 运行时,它没有做任何替换。
#!/bin/bash
# get new name string
name=$(xpath -q -e '/activity/page/name' page.xml);
en=$(echo $name|sed -e 's/<[^>]*>//g');
vi=$(echo $en|trans -brief -t vi);
cn=$(echo $en|trans -brief -t zh-CN);
mlang_name=$(echo "{mlang en}$en{mlang}{mlang
vi}$vi{mlang}{mlang
zh_cn}$cn{mlang}")
# xmlstarlet to update node
# get new content string
content=$(xpath -q -e '/activity/page/content' page.xml);
# \>(.*?)\<
mlang_name=$(echo $content|sed -e 's/\>(.*?)\</\{mlang
en\}$1\{mlang\}\{mlang
vi\}#VI#\{mlang\}\{mlang
zh_cn\}#CN#\{mlang\}/g')
# xmlstarlet to update node
我需要替换以将 {mlang en}TEXT{mlang} 放在文本周围。
解决方案
I ended up using perl as it supports the non-greedy format i was using.
perl -pe 's/(.*?>)(.*?)(<.*?)/$1\{mlang en\}$2\{mlang\}$3/g'
With the above file, the full command I used was
content=$(xpath -q -e '/activity/page/content' page.xml);echo $content|xargs|sed -e 's/<|<content>//g'|sed -e 's|</content>||g' |perl -pe 's/(.*?>)(.*?)(<.*?)/$1\{mlang en\}$2\{mlang\}$3/g'|sed -e 's/{mlang en}[\ ]*{mlang}//g'|sed -e 's/<content>//g'
Which gave the following output
<h3 style=float:right><img src=@@PLUGINFILE@@/consumables.png></h3><h3>{mlang en}TITLE{mlang}</h3><p>{mlang en}In order to conduct an LE5 drug test you need a Druglizaer (batch controlled) foil pouch that contains two items:{mlang}</p><p></p><ol><li><span style=font-weight:900>{mlang en}Druglizer LE5 Cartridge{mlang}</span></li><li><span style=font-weight:900>{mlang en}Druglizer Oral Fluid Collector{mlang}</span></li></ol><p></p>
If there's a more elegant way feel free to let me know.
推荐阅读
- c# - 反序列化不同类型的 JSON 数组
- javascript - 访问嵌套函数中的全局变量
- powershell - 我的 powershell 配置文件中的功能不显示?
- mysql - 从学生和教师表中选择
- c++ - 制作完成后是否可以将节点添加到图表中?
- python - Python input() 调用阻止其他线程打印到控制台
- c# - 将 C# PageAsyncTask() 转换为 VB.Net 等效的问题
- java - 如何从不同的活动中获取 RadioGroup 的价值
- swift4 - 使用 Codable 将 JSON 转换为 Swift 对象
- python - 执行 windows shell 命令并处理输出变量