Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

a regex question in java

Status
Not open for further replies.

keak

Programmer
Sep 12, 2005
247
0
0
CA
Hi there, I have a string
attrbute1="value1" attribute2="value2" attribute3="value3"

and I need to replace value2 with another string.

This is what I have so far, but this replaces the term 'attribute2' with the string. How would I replace value2 (value2 can be any random string)

p = Pattern.compile("attribute2");
m = p.matcher(instring);
outstring = m.replaceAll(repalce_with_string);

 
Code:
p = Pattern.compile(attribute2);
m = p.matcher(instring);
outstring = m.replaceAll(repalce_with_string);
or simplified
Code:
outstring = instring.replaceAll(attribute2, repalce_with_string);

seeking a job as java-programmer in Berlin:
 
Doh, the quotes. I won't answer a post before the first coffee anymore. I'm so sorry.

Anyway, pattern world is always a surprise for me. Will the regex really recognize the key=value series inside a String without any further information?

Cheers,
Dian
 
Actually waht I need replace is the text 'value2' and not attribute2 (given that value2 can be any random string).

The suggestions so far does a replace on the string "attribute2" and not "value2" I think ...
 
Perhaps you can give a concrete example.
Is your String something like
Code:
String input="attrbute1=\"value1\" attribute2=\"value2\" attribute3=\"value3\";
?
and you want to replace the second quoted element in that String?

What can we assume about that element?
Especially: can that element contain additional quotes and / or equal-signs/ blanks?

If not it will be easy:
A sequence, containing no quote, followed by a quote is:
[^"]*"
but for Java we have to mask the quote:
[^\"]*\"

We are interested in the part between quote 3 and 4:
Code:
String input = "attrbute1=\"value1\" attribute2=\"value2\" attribute3=\"value3\"";
System.out.println ("input:\t" + input);
String pattern = "([^\"]*\"[^\"]*\"[^\"]*\")([^\"]*)(\".*)";
System.out.println ("pattern:\t" + pattern);
String result = input.replaceAll (pattern, "$1foo$3");

seeking a job as java-programmer in Berlin:
 
One day someone has to tell me the differences between regular expression and assembler ...

Cheers,
Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top