使用Golang和正则表达式去掉外部标签?

huangapple go评论74阅读模式
英文:

get rid of the outer tag using golang and regexp?

问题

我正在使用goalng进行一些模板操作,并希望去掉外部的标签。如下所示:

input := `aaa<div><dxh r="4" spans="1:15"><c r="A4" s="7"><v>{{4567}}</v></c><c r="B4" t="s" s="7"><v>11</v></c><c r="C4" t="s" s="7"><v>12</v></c><c r="M4" t="s" s="8"><v>20</v></c></dxh>aaa</div>bbb<dxh>{{12345}}</dxh>amrambler`

我想要获取字符串,即去掉"<dxh ....>""</dxh>"标签,只保留它们之间的内容,即"{{4567}}""{{12345}}"

str := `aaa<div>{{4567}}aaa</div>bbb{{12345}}amrambler`

提前感谢!

英文:

I am using the goalng to do some template,and want to get rid of the outer tag .
as the following:

  input := `aaa<div><dxh r="4" spans="1:15"><c r="A4" s="7"><v>{{4567}}

</v></c><c r="B4" t="s" s="7"><v>11</v></c><c r="C4" t="s" s="7"><v>12</v>

</c><c r="M4" t="s" s="8"><v>20</v></c></dxh>aaa</div>bbb<dxh>{{12345}}

</dxh>amrambler`

and i want to get the string. it ommit the tag "<dxh ....>","</dxh>" . and only remain the content between them, "{{4567}}" and "{{12345}}"

str=`aaa<div>{{4567}}aaa</div>bbb{{12345}}amrambler`

thanks in advance !

答案1

得分: 1

你可以使用以下代码来获取你想要的输出。

package main

import (
   "fmt"
   "regexp"
)

func main() {
    re := regexp.MustCompile(`(?s)<dxh[^>]*>.*?({{[^}]*}}).*?</dxh>`)

    input := `aaa<div><dxh r="4" spans="1:15"><c r="A4" s="7"><v>{{4567}}
              </v></c><c r="B4" t="s" s="7"><v>11</v></c><c r="C4" t="s" s="7"><v>12</v>
              </c><c r="M4" t="s" s="8"><v>20</v></c></dxh>aaa</div>bbb<dxh>{{12345}}
              </dxh>amrambler`

    res := re.ReplaceAllString(input, "$1")
    fmt.Println(res) // aaa<div>{{4567}}aaa</div>bbb{{12345}}amrambler  
}

[kbd]**GoPlay**(http://play.golang.org/p/PdOEt0_ayf)[/kbd]

请注意,这只是代码的翻译部分,不包括代码的执行结果。

英文:

You can use the following to get your desired output.

package main

import (
   &quot;fmt&quot;
   &quot;regexp&quot;
)

func main() {
    re := regexp.MustCompile(&quot;(?s)&lt;dxh[^&gt;]*&gt;.*?({{[^}]*}}).*?&lt;/dxh&gt;&quot;)

    input := `aaa&lt;div&gt;&lt;dxh r=&quot;4&quot; spans=&quot;1:15&quot;&gt;&lt;c r=&quot;A4&quot; s=&quot;7&quot;&gt;&lt;v&gt;{{4567}}
              &lt;/v&gt;&lt;/c&gt;&lt;c r=&quot;B4&quot; t=&quot;s&quot; s=&quot;7&quot;&gt;&lt;v&gt;11&lt;/v&gt;&lt;/c&gt;&lt;c r=&quot;C4&quot; t=&quot;s&quot; s=&quot;7&quot;&gt;&lt;v&gt;12&lt;/v&gt;
              &lt;/c&gt;&lt;c r=&quot;M4&quot; t=&quot;s&quot; s=&quot;8&quot;&gt;&lt;v&gt;20&lt;/v&gt;&lt;/c&gt;&lt;/dxh&gt;aaa&lt;/div&gt;bbb&lt;dxh&gt;{{12345}}
              &lt;/dxh&gt;amrambler`

    res := re.ReplaceAllString(input, &quot;$1&quot;)
    fmt.Println(res) // aaa&lt;div&gt;{{4567}}aaa&lt;/div&gt;bbb{{12345}}amrambler  
}

<kbd>GoPlay</kbd>

huangapple
  • 本文由 发表于 2015年1月22日 09:12:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/28079788.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定