regex - Can i get a appropriate regular expression for the following string in java with the following condition -
the test string is
it test data %warning: portfast should enabled on ports connected single host. connecting hubs, concentrators, switches, bridges, etc. interface when portfast enabled can cause temporary bridging loops. use caution test test.
the string invalid if string has %
symbol in it. valid if %
followed following sequence of characters, "%warning: portfast should enabled on ports connected single\n host. connecting hubs, concentrators, switches, bridges, etc. this\n interface when portfast enabled can cause temporary bridging loops.\n use caution".even in case '%' symbol can present once.
my code is:
public class abc { public static void main(string[] args) { string reg="%(warning: portfast should enabled on ports connected single\n host. connecting hubs, concentrators, switches, bridges, etc. this\n interface when portfast enabled can cause temporary bridging loops.\n use caution)([^%])"; string str = "%warning: portfast should enabled on ports connected single\n host. connecting hubs, concentrators, switches, bridges, etc. this\n interface when portfast enabled can cause temporary bridging loops.\n use cautiontest testdata invalid%"; pattern regex2 = pattern .compile(reg); matcher matcher = regex2.matcher(str); if (matcher.find()) { system.out.println("valid"); } else { system.out.println("invalid"); } } }
but not getting expected. can suitable regular expression?
maybe combile code expression gets count of '%'
public static void main(string[] args) { string reg = "%warning: portfast should enabled on ports connected single\n host. connecting hubs, concentrators, switches, bridges, etc. this\n interface when portfast enabled can cause temporary bridging loops.\n use caution"; string str = "%warning: portfast should enabled on ports connected single\n host. connecting hubs, concentrators, switches, bridges, etc. this\n interface when portfast enabled can cause temporary bridging loops.\n use cautiontest testdata invalid%"; pattern regex2 = pattern.compile(reg); matcher matcher = regex2.matcher(str); int occurences = str.length() - str.replace("%", "").length(); if (matcher.find() && occurences <= 1) { system.out.println("valid"); } else { system.out.println("invalid"); } }
if have stringutils class can use method countmatches
Comments
Post a Comment