首页 > 解决方案 > 为什么我的正则表达式在在线正则表达式测试仪上运行时无法选择正确的元素

问题描述

我有许多 xml 文件,它们在 node 中嵌入了 HTML。我需要捕获所有不是标签的东西,在文本周围添加一些非 HTML 标签(用于moodle)。

我正在使用 bash 脚本从命令行处理文件。我正在使用 xpath 来获取内容,通过 xargs 管道偷偷地撕掉换行符,然后通过 sed 管道。

下面是一个标签示例:

xpath -q -e '/activity/page/content' page.xml|xargs
<content>&lt;h3 style=float:right>&lt;img
src=@@PLUGINFILE@@/consumables.png> &lt;/h3> &lt;h3>TITLE&lt;/h3> 
&lt;p>In order to conduct an LE5 drug test you need a Druglizaer 
(batch controlled) foil pouch that contains two items:&lt;/p> 
&lt;p>&lt;/p> &lt;ol> &lt;li>&lt;span style=font- 
weight:900>Druglizer Cartridge&lt;/span>&lt;/li>&lt;li>&lt;span 
style=font-weight:900>Druglizer Oral Fluid
Collector&lt;/span>&lt;/li> &lt;/ol> &lt;p>&lt;/p></content>

https://regex101.com/上,我使用\&gt;(.*?)\&lt;了按预期对文本进行分组。但是当我使用 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 "&#123;mlang en&#125;$en&#123;mlang&#125;&#123;mlang 
 vi&#125;$vi&#123;mlang&#125;&#123;mlang 
 zh_cn&#125;$cn&#123;mlang&#125;")
 # xmlstarlet to update node

 # get new content string
 content=$(xpath -q -e '/activity/page/content' page.xml);
 # \&gt;(.*?)\&lt;
 mlang_name=$(echo $content|sed -e 's/\&gt;(.*?)\&lt;/\&#123;mlang 
 en\&#125;$1\&#123;mlang\&#125;\&#123;mlang 
 vi\&#125;#VI#\&#123;mlang\&#125;\&#123;mlang 
 zh_cn\&#125;#CN#\&#123;mlang\&#125;/g')
 # xmlstarlet to update node

我需要替换以将 {mlang en}TEXT{mlang} 放在文本周围。

标签: regexbashubuntused

解决方案


I ended up using perl as it supports the non-greedy format i was using.

perl -pe 's/(.*?>)(.*?)(&lt;.*?)/$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/(.*?>)(.*?)(&lt;.*?)/$1\{mlang en\}$2\{mlang\}$3/g'|sed -e 's/{mlang en}[\ ]*{mlang}//g'|sed -e 's/<content>//g'

Which gave the following output

&lt;h3 style=float:right>&lt;img src=@@PLUGINFILE@@/consumables.png>&lt;/h3>&lt;h3>{mlang en}TITLE{mlang}&lt;/h3>&lt;p>{mlang en}In order to conduct an LE5 drug test you need a Druglizaer (batch controlled) foil pouch that contains two items:{mlang}&lt;/p>&lt;p>&lt;/p>&lt;ol>&lt;li>&lt;span style=font-weight:900>{mlang en}Druglizer LE5 Cartridge{mlang}&lt;/span>&lt;/li>&lt;li>&lt;span style=font-weight:900>{mlang en}Druglizer Oral Fluid Collector{mlang}&lt;/span>&lt;/li>&lt;/ol>&lt;p>&lt;/p>

If there's a more elegant way feel free to let me know.


推荐阅读