Tuesday, 20 August 2013

Replace all spaces in the key of a property file

Replace all spaces in the key of a property file

I would like to escape all keys that contain spaces in a Java properties
file by adding a \ before them
Example input
prop with spaces=value with spaces
#comment should not be replaced
prop_without_spaces=value with spaces 2
Desired output:
prop\ with\ spaces=value with spaces
#comment should not be replaced
prop_without_spaces=value with spaces 2
I know I can replace all spaces with
<replaceregexp byline="true" flags="g" match="\s" replace="\\\\ "
file="..."/>
But it renders this result
prop\ with\ spaces=value\ with\ spaces
#comment\ should\ not\ be\ replaced
prop_without_spaces=value\ with\ spaces\ 2
Or I can do something like this ^(([^=])|(\s))*(=.*) to match the various
groups, but then how do I replace all spaces, e.g. how do I reconstruct
the result to include only the non spaces?
In other words, given an input as above, how do I do the following pseudo
code, in regex:
for rows that don't start with a #
for all chars before the first = sign
replace all " " (spaces) with a "\ " (forward slash, space)
Is that possible in RegEx in general, and in Java in particular?
(preferably ANT replaceregexp example)

No comments:

Post a Comment