Regex pattern matching
Hello everyone I need a regex to replace everything inside de src= and /> tag on this line
src="../../../../../mailPho开发者_Go百科tos/assasins1.jpeg" alt="" width="284" height="177" /></p>
The code I'm trying for the regex is the following:
String regex="src=\"../../../../../ndeveloperDocuments/mailPhotos/assasins1.jpeg\" alt=\"\" width=\"284\" height=\"177\" /></p>";
regex=regex.replaceFirst("src./>", "src='cid:"+1001+"'");
But it's not replacing anything. What I though is that the regex would do something like "replace everything between src and />", but think I'm wrong as it doesn't work. What would be a regex to use in this case?.Thanks a lot
.
only matches one character. To match zero or more characters, use .*
and to match one or more characters use .+
.
So, your code would be:
String regex="src=\"../../../../../ndeveloperDocuments/mailPhotos/assasins1.jpeg\" alt=\"\" width=\"284\" height=\"177\" /></p>";
regex=regex.replaceFirst("src.*/>", "src='cid:"+1001+"'");
A .
only matches a single character. To match any number of single characters, use .*
(0 or more) or .+
(1 or more).
It's easy for this kind of matching to go wrong, however. For example, if you have a string like src="foo" /> Some other content <br />
your regex will match all the way to the final />
and swallow up tyhe other content. A common way to prevent this is to use a regex like src=[^>]+/>
. The [^>]
means "any character except >
.
精彩评论