should not consider the white space at the end of the string or the white space in between two digits, but it can be either preceding or followed by a digit but not in between digits. I wrote a regex expression ,but it is not working for all conditions according to my requirement.
Pattern pattern =Pattern.compile("\\s(?![\\d\\s]*\\d$)");
Matcher matcher=pattern.matcher(input);
int lastIndex=-1;
while(matcher.find()){
lastIndex=matcher.start());
}
how can i achieve my requirement using regex expression and any other way to get last occurrence without while loop? Example
jumnsch@domain.com m 5180-3807-3679-8221 612 3/1/2010
^
hello this card number 4444 5555 6666 7777
^
hello this bob
^
You could use a look-ahead assertion:
Assert that the candidate space is followed by at least one non-white space character and any further white space (if any) is surrounded by digits or occurs at the end of the string.
For that "surrounding" condition you can again use look-around assertions. This regex will only match white space that is surrounded by digits or occurs at the end of the string with a preceding digit: "(?<=\\d)\\s+(?!\\D)"
. Only that type of white space and \\s*$
will be allowed after the potentially matched space with this assertion:
"(?=\\S+((?<=\\d)\\s+(?!\\D)\\S*)*\\s*$)"
Now we could add the requirement of the candidate space itself: that it should either have no digit before it, or no digit following it:
"(?:\\s(?=\\D)|(?<!\\d)\\s)(?=\\S+((?<=\\d)\\s+(?!\\D)\\S*)*\\s*$)"
Code:
Pattern pattern = Pattern.compile("(?:\\s(?=\\D)|(?<!\\d)\\s)(?=\\S+((?<=\\d)\\s+(?!\\D)\\S*)*\\s*$)");
Matcher matcher = pattern.matcher(input);
int lastIndex=-1;
if (matcher.find()) { // We only expect at most one match
lastIndex = matcher.start();
// Do something with lastIndex
}