Ищите Wildcard ('<', '>'), посчитайте его и получите позицию в java - PullRequest
1 голос
/ 28 июня 2010

Я хочу найти Wildcard ('<', '>') в строке, посчитать их и получить их позиции в Java.Моя строка выглядит примерно так:

Питер <5554>, Джон <5556>,

, какую функцию мне использовать?Спасибо.

Ответы [ 4 ]

3 голосов
/ 28 июня 2010

Вы должны использовать Pattern и Matcher :

Pattern pattern = Pattern.compile("<[^>]*>");
Matcher matcher = pattern.matcher("Peter <5554>, John <5556>,");
while (matcher.find()) {
   System.out.println("index="+matcher.start()+" - "+matcher.group());
}

Выход:

index=6 - <5554>
index=19 - <5556>
2 голосов
/ 28 июня 2010

Вы можете реализовать это с повторными indexOf и substring:

String s = "Peter <5554>, John <5556>,"
int count = 0;
ArrayList<Integer> positions = new ArrayList<Integer>();
int cut = 0;
while(true) {
  // search for <
  int index = s.indexOf('<');
  if (index < 0)
    break;
  // search for >
  int index2 = s.indexOf('>');
  if (index2 < 0)
    break; // or throw exception

  // update count and positions
  count++;
  positions.add(index+cut);

  s = s.substring(index2+1);
  cut += index2+1; // used to compute the initial position since we're cutting the string
}
2 голосов
/ 28 июня 2010

Одним из решений было бы использование String.indexOf (). Вы можете сделать что-то вроде этого:


String s = "Peter <5554>, John <5556>";
List<Integer> posGt = new ArrayList<Integer>();
int i = 0;
while((i = s.indexOf('>', i)) != -1) {
   posGt.add(i++);
}
...
//the same for <
0 голосов
/ 28 июня 2010

Повтор indexOf с fromIndex выглядит как хорошее решение.Альтернативой было бы перебрать строку и использовать charAt (возможно, очевидное решение, если бы только у java была нормальная индексация строки):

String s = "Peter <5554>, John <5556>,";
for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) == '<' || s.charAt(i) == '>') {
        System.out.printf("index %d - %s\n", i, s.charAt(i));
    }
}
...