Поймать подобные слова в линииJAVA

Программисты JAVA общаются здесь
Anonymous
Поймать подобные слова в линии

Сообщение Anonymous »

У меня ниже строка. < /p>

Код: Выделить всё

What is (Jim)'s gift (limit)?  Personname  Amount::Spent
in this line I want to find and print the start and end positions of ( and ).

In my current code, I'm able to print it, but the problem is, it is getting printed multiple times (I'm sure that this is because of the while).

My code is as ниже. < /p>

String line = "What is (Rakesh)'s gift (limit)? Personname Amount::Spent";
if (line.contains("")) {
String[] example_split = line.split("", 2);
System.out.println("String is " + example_split[1]);
if (example_split[0].length() > 1) {
String[] example_entity = example_split[1].split("");

for (String splitStrings : example_entity) {
int openParamCount = line.length() - line.replace("(", "").length();
int closeParamCount = line.length() - line.replace("(", "").length();
System.out.println(openParamCount + "\t" + closeParamCount);
if (!(openParamCount == closeParamCount))
System.out.println("Paranthesis don't match for " + line);
if (!(openParamCount == example_entity.length))
System.out.println(
"The entities provided and the words marked in paranthesis don't match for " + line);

int entities_count = 0;
int no_of_entities = example_entity.length;
Set utterancesSet = new HashSet();
int startPosition = 0;
int endPosition = 0;
while (entities_count < no_of_entities) {
List matchList = new ArrayList();
Pattern regex = Pattern.compile("\\((.*?)\\)");
Matcher regexMatcher = regex.matcher(line);
while (regexMatcher.find()) {
startPosition = regexMatcher.start() + 1;
endPosition = regexMatcher.start() - 1;

matchList.add(regexMatcher.group(1));
System.out.println("start position is " + startPosition + " end position is " + endPosition
+ " Entity Type" + example_entity[entities_count]);
}
entities_count++;
}
}
}
}
< /code>

Ожидаемый вывод: < /p>

String is Personname Amount::Spent
2 2
start position is 9 end position is 12 Entity Type Personname
start position is 22 end position is 27 Entity Type Amount::Spent
< /code>

текущий вывод < /p>

String is Personname Amount::Spent
2 2
start position is 9 end position is 12 Entity Type Personname
start position is 22 end position is 27 Entity Type Personname
start position is 9 end position is 12 Entity Type Amount::Spent
start position is 22 end position is 27 Entity Type Amount::Spent
2 2
start position is 9 end position is 12 Entity Type Personname
start position is 22 end position is 27 Entity Type Personname
start position is 9 end position is 12 Entity Type Amount::Spent
start position is 22 end position is 27 Entity Type Amount::Spent
< /code>

Пожалуйста, дайте мне знать, где я ошибаюсь и как я могу это исправить. < /p>

спасибо < /p>

Подробнее здесь: https://stackoverflow.com/questions/429 ... -in-a-line

Вернуться в «JAVA»