The problem I’m facing here is that the current regex I created does not fully work. If there is no white space at the end of my String it fails. My question is there any way to resolve this?
Here are the details of the question:
I need a regex that ensures Strings conform to the following format,
“LL=xxxxxx LL=xxxxxxxxx LL=xxxxxxx”
L = Letter.
X = Letter or number or punctuation mark.
The closest regex I have is,
([\\pL]{2}=[\\pL|\\pN|\\pP]+ )+
But this regex does not work and will only work if the String is in the Format:
“LL=xxxxxx LL=xxxxxxxxx LL=xxxxxxx ”
Here is code I use to check:
final String regex1 = "([\\pL]{2}=[\\pL|\\pN|\\pP]+ )+";
String x = "xx=xxxxxx xx=xxxxxxxxxm xx=xxxxxxx xx=xxxxxxx"; // This is what I need!
String y = "xx=xxxxxx xx=xxxxxxxxxm xx=xxxxxxx xx=xxxxxxx "; // This works, no good
System.out.println(x.matches(regex1));
System.out.println(y.matches(regex1));
Replace the space with
(?: |\z)and it should work.The
(?: |\z)is a non-capturing group that matches a space or end of input.Note that in
[\\pL|\\pN|\\pP], the|does not mean “or”. You probably want[\\pL\\pN\\pP]which means any one of any letter, number, or punctuation character.