ruby - Replacing text from a file with regular expressions -
i'm trying read xml file , substitute dp
sp
everywhere in text textsize attribute used. example android:textsize="8dp"
replaced android:textsize="8sp"
if below file processed:
<?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>
and have following code:
patterndp = /android:textsize=\"[\d]+dp\"/ content = file.read("layout/some_layout.xml") content.gsub!(patterndp, "???")
i know second parameter of gsub!
method string replace pattern, , have difficulties on how use in such way method not replace whole android:textsize="8dp"
sp
, dp
string pattern.
would appreciate help, if approach not correct please let me know how solve problem in way.
capture digit(\d+
) , use \\1
in replacement obtain capture.
input = input.gsub(/(?<=android:textsize=")(\d+)dp"/, '\\1sp"')
(?<=android:textsize=")
checking whether digits after android:textsize="
text or not doesn't pick others.
however, if not wish use lookbehind (?<=...)
simple one.
input = input.gsub(/android:textsize="(\d+)dp"/, 'android:textsize="\\1sp"')
Comments
Post a Comment