簡體   English   中英

什么是正則表達式,找到這樣的行: <rect **** />

[英]What is a regular expression that find a line like this: <rect **** />

我想要一個可用於查找以下行的正則表達式:

<rect width='10px' height ='20px'/>
<rect width='20px' height ='22px'/>
<circle radius='20px' height ='22px'/>

並用以下代碼替換它們:

<rect width='10px' height ='20px'></rect>
<rect width='20px' height ='22px'></rect>
<circle radius='20px' height ='22px'></circle>

謝謝 。

像polygenelubricants一樣,我不知道這會實現什么,但這應該是你正在尋找的:

<rect[^>]*/>

<circle[^>]*/>

如果你想匹配任何自包含的標簽,你應該看看Crozins解決方案。

你可以使用這樣的東西#<([az]+)([^>]*)/>#並替換為<$1$2></$1> 但正則表達式可能會有所不同,具體取決於您正在使用的正則表達式引擎。

sed 's/<\\([az]*\\) \\([^\\/>]*\\)\\/>/<\\1 \\2><\\/\\1>/'

會做你想要的(在這種情況下)

搜索模式: <\\([az]*\\) \\([^\\/>]*\\)\\/>

替換模式: <\\1 \\2><\\/\\1>

我不認為正則表達式是這項工作的正確工具,但這樣的事情在某些時候會“起作用”。

    String text =
        " <rect width='10px' height ='20px'/> \n" +
        " <rect width='20px' height ='22px'/> \n" +
        " <circle radius='20px' height ='22px'/> \n" +
        " <square/> <rectangle></rectangle> \n" +
        " <foo @!(*#&^#@/> <bar (!@*&(*@!#> </whatever>";
    System.out.println(
        text.replaceAll("<([a-z]+)([^>]*)/>", "<$1$2></$1>")
    );

上面的Java代碼段打印:

 <rect width='10px' height ='20px'></rect> 
 <rect width='20px' height ='22px'></rect> 
 <circle radius='20px' height ='22px'></circle> 
 <square></square> <rectangle></rectangle> 
 <foo @!(*#&^#@></foo> <bar (!@*&(*@!#> </whatever>

正則表達式是這樣的( 參見rubular.com ):

/<([a-z]+)([^>]*)\/>/

基本上我們嘗試捕獲我們希望組1中的標記名稱,以及其他所有內容,直到組2中的/> ,並在替換中使用這些捕獲的字符串。

參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM