Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to search a string for 6 random numbers

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

What would be the best way to achieve this? Thank you for looking into this.

like image 826
DVPeer Avatar asked Oct 01 '12 21:10

DVPeer


3 Answers

You could use regex.

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());
}

This would do the job.

(Code sample from here)

like image 191
La bla bla Avatar answered Nov 02 '22 07:11

La bla bla


Use Character.isDigit while iterating the string's characters and then count a number up until you have found 6 consecutive numbers or reset it if the sequence breaks. Keep track of the index and you can simply calculate the nearest position by subtraction.

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

like image 31
Konrad Reiche Avatar answered Nov 02 '22 07:11

Konrad Reiche


An effective approach would be to iterate the characters of the string and test if each is a digit. Upon finding a match continue to look for the rest of the sequence. Something like

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"
  }
}
like image 42
Johan Sjöberg Avatar answered Nov 02 '22 06:11

Johan Sjöberg