Ruby 用正则表达式替换文件中的文本
我试图读取一个XML文件,并用Ruby 用正则表达式替换文件中的文本,ruby,regex,Ruby,Regex,我试图读取一个XML文件,并用sp替换使用textSize属性的文本中的所有位置。例如,如果将处理以下文件,则将用android:textSize=“8dp”替换android:textSize=“8sp”: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
sp
替换使用textSize属性的文本中的所有位置。例如,如果将处理以下文件,则将用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>
我知道gsub的第二个参数
method是将替换模式的字符串,我在如何使用它时遇到了一些困难,即该方法不能将整个android:textSize=“8dp”
替换为sp
,而只能替换模式中的dp
字符串
如果我的方法不正确,请告诉我如何用另一种方法解决问题。捕获数字(\d+
),并使用\\1
替换以获取捕获
input = input.gsub(/(?<=android:textSize=")(\d+)dp"/, '\\1sp"')
非常感谢。工作起来很有魅力!不要用正则表达式解析XML;正则表达式不是很好的工具,除非在最简单的情况下控制XML的生成。如果XML格式发生更改,您的模式很可能会中断。在这种情况下,您可以使用一个简单的
gsub
,因为您没有尝试匹配标记,但在大多数情况下,您最好使用Nokogiri并学习以正确的方式解析XML/HTML。很高兴知道,谢谢。
input = input.gsub(/(?<=android:textSize=")(\d+)dp"/, '\\1sp"')
input = input.gsub(/android:textSize="(\d+)dp"/, 'android:textSize="\\1sp"')