I am in a strict Java environment.
So the question is not really as simple as in the tite, I am not trying to solve a problem I have, it is more theoretical for better knowledge.
What I am interested in is matching against src with either double or simple quote, but if it is double quote, it also has to be closed with a double quote, and same applies to simple quote.
I am aware of that i can repeat the regex in itself, ie:
String str = "src=\"hello/\" ... src='hello/' ..."
println str.replaceAll ("src=((\"[^\"]+\")|('[^']+'))", "src=$1")
What I would like to do is like:
println s.replaceAll ("src=([\"'][^\"']+[\"'])", "src=$1")
However, if it starts with double quote, then simple quotes should be allowed in the content, and it must end with a double quote, not a simple quote.
Question 2:
Is it possible to have it replaceAll with the same type of quote that was found? Is it possible to say, for this match, replace with this2, for that, replace with that2. How can you accomplish this without generating a new string each time?
Edit for Alan More, example for question two:
println "one ... two".replaceAll( "(one)", "1" ).replaceAll("(two)", "2");
more along these lines ( not right )
println "one ... two".replaceMyMatches( "(one)[^\\w]+(two)", "\$1{1}, \$2{2}" ) // prints string : one{1}, two{2}
What I want is the string: 1, 2
Answer for first question derived and altered a bit from black panda and Jeff Walker:
String str = "src=\"1.png\" ... src='2.jpeg' ... src=\"3.p'ng\" ... src='4.jpe\"g' ... src='' ... src=\"\" ..." ;
String regex = "src=(['\"])(.+?)\\1"; // closes with the quote that is in group 1
println str.replaceAll( regex, '''src=$1../new_path/$2$1''')
Spits out:
src="../new_path/1.png" ... src='../new_path/2.jpeg' ... src="../new_path/3.p'ng" ... src='../new_path/4.jpe"g' ... src='' ... src="" ...
If one wants to replace the empty ones as well, just switch the + in the regex against a star ( I don't want that )
Notice the original quotes are in as well.
Answer question two see black panda