0

我想匹配一个属性的多个值以进行替换。例如

<div class="div h1 full-width"></div>

应该产生 div、h1 和 full-width 作为单独的匹配项。我想这样做为类添加前缀。所以而不是 div h1 full-width 它应该是 pre-div pre-h1 pre-full-width

我到目前为止的正则表达式是

(?<=class=["'])(\b-?[_a-zA-Z]+[_a-zA-Z0-9-]*\b)+

这仅匹配第一类。这是不正常的,因为这是该模式应该匹配的唯一内容:(在类属性的引号之间单独匹配任何值。

我想为处理所有文件并用设置的前缀替换 class="value1 value2 value3" 的 Ant 构建脚本执行此操作。我在替换 css 文件中的类时几乎没有遇到任何麻烦,但你的 html 似乎要复杂得多。

它是一个 Ant 构建脚本。Java regexp 包用于处理模式。使用的ant标签是:replaceregexp

上述模式的蚂蚁实现是:

<target name="prefix-class" depends="">
  <replaceregexp flags="g">
    <regexp  pattern="(?&lt;=class=['&quot;])(\b-?[_a-zA-Z]+[_a-zA-Z0-9-]*\b)+"/>
    <substitution expression=".${prefix}\1"/>
    <fileset dir="${dest}"/>
   </replaceregexp>
</target>    
4

2 回答 2

0

我不认为您可以找到 n 个(或在您的情况下为 3 个)不同的类条目并将它们替换为一个简单的正则表达式。如果您需要在 ant 中执行此操作,我认为您必须编写自己的 ant 任务。更好的方法是 xslt,你熟悉 xslt 吗?

于 2011-07-26T12:21:02.017 回答
0

放弃了 Ants ReplaceRegExp 并使用 XSLT 对我的问题进行了排序,以将 xhtml 转换为 xhtml。

以下代码为元素类属性的所有值添加前缀。xhtml 源文档必须正确格式化才能被解析。

<xsl:stylesheet version="2.0"
xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:fn="http://www.w3.org/2005/xpath-functions"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xhtml xsl xs">

  <xsl:output method="xml" version="1.0" encoding="UTF-8" 
    doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" 
    doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1.dtd" 
    indent="yes" omit-xml-declaration="yes"/>

  <xsl:param name="prefix" select="'oo-'"/>

  <xsl:template match="/">
    <xsl:apply-templates select="./@*|./node()" />
  </xsl:template>

  <!--remove these atts from output, default xhtml values from dtd -->
  <xsl:template match="xhtml:a/@shape"/>
  <xsl:template match="@rowspan"/>
  <xsl:template match="@colspan"/>

  <xsl:template match="@class">
    <xsl:variable name="replace_regex">
      <xsl:value-of select="$prefix"/>
      <xsl:text>$1</xsl:text>
    </xsl:variable>
    <xsl:attribute name="class">
      <xsl:value-of select="fn:replace( . , '(\w+)' , $replace_regex )"/>
    </xsl:attribute>
  </xsl:template>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
于 2011-07-27T00:27:26.880 回答