簡體   English   中英

用正則表達式替換文件中的文本

[英]Replacing text from a file with regular expressions

我正在嘗試讀取XML文件,並在使用textSize屬性的文本中的任何地方用sp代替dp 例如,如果將處理以下文件,則android:textSize="8dp"將替換為android:textSize="8sp"

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content" >

    <TextView
            android:id="@+id/description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="8dp"/>

    <View            
            android:layout_width="wrap_content"
            android:layout_height="5dp" />

</LinearLayout>

我有以下代碼:

patternDp = /android:textSize=\"[\d]+dp\"/
content = File.read("layout/some_layout.xml")
content.gsub!(patternDp, "???")

我知道gsub!的第二個參數gsub! 方法是將替換模式的字符串,並且我在如何以某種方式使用它方面遇到了一些困難,即該方法不能用sp替換整個android:textSize="8dp" ,而不能替換模式中的dp字符串。

如果我的方法不正確,請提供幫助,請告訴我如何用其他方法解決問題。

捕獲數字( \\d+ )並使用\\\\1代替獲取捕獲。

input = input.gsub(/(?<=android:textSize=")(\d+)dp"/, '\\1sp"')

(?<=android:textSize=")檢查數字是否在android:textSize="文本之后,以便它不會選擇其他數字。

但是,如果您不希望使用lookbehind (?<=...) ,請使用此簡單方法。

input = input.gsub(/android:textSize="(\d+)dp"/, 'android:textSize="\\1sp"')

暫無
暫無

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

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