oLEG
oLEG

Reputation:

Regular Expression: How to put single quotes around XML attribute values?

i have a string that looks like

"<input id=a/>"<input id=b/>"<input id=c/>etc.

I need to change it to

"<input id='a'/>"<input id='b'/>"<input id='c'/>etc,

any ideas how?

Upvotes: 5

Views: 1910

Answers (3)

Jan Goyvaerts
Jan Goyvaerts

Reputation: 21999

It's hard to really answer this with just one small sample. For the given sample text, you can search for the regex:

=(\w)

and replace it with:

='$1'

or:

='\1'

Depending on whether the programming language you're working with interprets $1 or \1 as a reference to the first capturing group in the replacement text.

This trivial search-and-replace works perfectly on your given sample text.

I fear that it won't work on your actual data. If that's the case, then that's because your sample text isn't representative of your actual data. The hardest part in creating regular expressions is to figure out what you want to match, and what you don't want to match. This is something you have to specify in your question.

Upvotes: 0

Renaud Bompuis
Renaud Bompuis

Reputation: 16786

In C# you could write it as:

resultString = Regex.Replace(subjectString, @"(<.*?id\s*=\s*)(\w+)(.*?>)", "$1'$2'$3", RegexOptions.Multiline);

In VB.Net it would simply be:

ResultString = Regex.Replace(SubjectString, "(<.*?id\s*=\s*)(\w+)(.*?>)", "$1'$2'$3", RegexOptions.Multiline)

In canonical Perl, you could write it as:

$subject =~ s/(<.*?id\s*=\s*)(\w+)(.*?>)/$1'$2'$3/mg;

In PHP:

$result = preg_replace('/(<.*?id\s*=\s*)(\w+)(.*?>)/m', '$1\'$2\'$3', $subject);

In Java:

resultString = subjectString.replaceAll("(?m)(<.*?id\\s*=\\s*)(\\w+)(.*?>)", "$1'$2'$3");

In Javascript:

result = subject.replace(/(<.*?id\s*=\s*)(\w+)(.*?>)/mg, "$1'$2'$3");

Upvotes: 4

foxdonut
foxdonut

Reputation: 7947

How about this:

%s/"<input id=\(.\)\/>/"<input id='\1'\/>/g

This would also work:

%s/\("<input id=\)\(.\)\/>/\1'\2'\/>/g

Upvotes: 1

Related Questions