java - When the following Regex matches? -
i found following regex in 1 of android source file:
string regex = "\\s+(?i)src=\"cid(?-i):\\q" + attachment.mcontentid + "\\e\""; if(string.matches(regex)) { print -- matched } else { print -- not found }
note: attachment.mcontentid have values c4ea83841e79f643970af3f20725cb04@gmail.com
i made sample code below:
string content = "hello src=\"cid:something@gmail.com\" present"; string contentid = "something@gmail.com"; string regex = "\\s+(?i)src=\"cid(?-i):\\q" + contentid + "\\e\""; if(content.matches(regex)) system.out.println("present"); else system.out.println("not present");
this gives "not present" output.
but when doing below:
system.out.println(content.replaceall(regex, " replaced value"));
and output replaced new value. if not present, how replaceall work , replace new value? please clear confusions.
can kind of content in string make control go if part?
string regex = "\\s+(?i)src=\"cid(?-i):\\q" + attachment.mcontentid + "\\e\"";
break down:
\\s+ - match 1 or more spaces (?i) - turn on case-insensitive matching subsequent string src=\"cid - match src="cid (?-i) - turn off case-insensitive matching : - colon \\q - treat following stuff before \\e literal characters, , not control characters. special regex characters disabled until \\e attachment.mcontentid - whatever string \\e - end literal quoting sandwich started \\q \" - end quote
so match string src="cid:your-string-literal"
or, use own example, string match (there leading white space characters):
src="cid:c4ea83841e79f643970af3f20725cb04@gmail.com"
for update
the problem you're running using java.lang.string.matches()
, expecting think should.
string.matches()
(and matcher
) has problem: tries match entire string against regular expression.
if use regex:
string regex = "\\s+(?i)src=\"cid(?-i):\\q" + attachment.mcontentid + "\\e\"";
and input:
string content = "hello src=\"cid:something@gmail.com\" present";
content
never match regex
because entire string doesn't match regular expression.
what want use matcher.find
- should work you.
string content = "hello src=\"cid:something@gmail.com\" present"; string contentid = "something@gmail.com"; pattern pattern = pattern.compile("\\s+(?i)src=\"cid(?-i):\\q" + contentid + "\\e\""); matcher m = pattern.matcher(content); if(m.find()) system.out.println("present"); else system.out.println("not present");
ideone example: https://ideone.com/8rtf0e
Comments
Post a Comment