regex - Find and Replace a pattern of string in java -
i use regex , string replacefirst replace patterns below.
string xml = "<param>otpcode=1234567</param><param>password=abc123</param>"; if(xml.contains("otpcode")){ pattern regex = pattern.compile("<param>otpcode=(.*)</param>"); matcher matcher = regex.matcher(xml); if (matcher.find()) { xml = xml.replacefirst("<param>otpcode=" + matcher.group(1)+ "</param>","<param>otpcode=xxxx</param>"); } } system.out.println(xml); if (xml.contains("password")) { pattern regex = pattern.compile("<param>password=(.*)</param>"); matcher matcher = regex.matcher(xml); if (matcher.find()) { xml = xml.replacefirst("<param>password=" + matcher.group(1)+ "</param>","<param>password=xxxx</param>"); } } system.out.println(xml); desired o/p
<param>otpcode=xxxx</param><param>password=abc123</param> <param>otpcode=xxxx</param><param>password=xxxx</param> actual o/p (replaces entire string in single shot in first if itself)
<param>otpcode=xxxx</param> <param>otpcode=xxxx</param>
you need non-greedy regex:
<param>otpcode=(.*?)</param> <param>password=(.*?)</param> this match first </param> not last one...
Comments
Post a Comment