Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 用正则表达式替换文件中的文本_Ruby_Regex - Fatal编程技术网

Ruby 用正则表达式替换文件中的文本

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"

我试图读取一个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"
              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"')