Java - How to search a string for 6 random numbers

I have a (large) string file in my application that contains a series of random characters [aZ] and [0-9], but also ";", "/", "?", ":" And "@". I would like my application to tell me the nearest position, where 6 digits are displayed in sequence (for example, "105487" or "558463").

What would be the best way to achieve this? Thanks for looking at this.

+5
source share
3 answers

An efficient approach would be to iterate over the characters of the string and test if each digit. Once you find the match, keep looking for the rest of the sequence. Sort of

int nDigits=0, i = 0;
CharacterIterator it = new StringCharacterIterator("very long string123456");
for (char ch=it.first(); ch != CharacterIterator.DONE; ch=it.next()) {
  i++;
  nDigits = (ch.isDigit() ? nDigits++ : 0);
  if (nDigits == 5) {
      // DONE. Position is "i"
  }
}
+1
source

.

String regex = "(\\d{6})";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(YOU STRING HERE);
// Check all occurrences
while (matcher.find()) {
    System.out.print("Start index: " + matcher.start());
    System.out.print(" End index: " + matcher.end());
    System.out.println(" Found: " + matcher.group());
}

.

( )

+4

Use Character.isDigit when repeating string characters, and then count the number until you find 6 consecutive numbers or reset if the sequence is interrupted. Keep an eye on the index and you can simply calculate the closest position by subtracting it.

This is not very efficient, but I think O (n) is sufficient if the strings are not too large. For optimization, take a look at what Luigi Mendoza suggested in the comments.

+3
source

All Articles