Как получить строку, которая находится между двумя другими строками?
ex: У меня есть строка <str>hello this is stuff</str>
и я хочу получить то, что находится между <str>
и </str>
заранее спасибо
Хотя название вашего вопроса очень плохое, я точно знаю, о чем вы говорите, и у меня были проблемы с этим раньше. Решение использует шаблон.
Легкий способ получить строку, которая находится между <str>
и </str>
(что, как я предполагаю, вероятно, будет просто чем-то другим в HTML), заключается в следующем:
Сначала сначала инициализируйте шаблон, сделав это:
Pattern pattern = Pattern.compile("<str>(.*?)</str>"); // (.*?) means 'anything'
Затем вы хотите получить от него помощник, выполнив следующие действия:
Matcher matcher = pattern.matcher(<str>); //Note: replace <str> with your string variable, which contains the <str> and </str> codes (and the text between them).
Затем, в зависимости от того, хотите ли вы найти последнее совпадение или первое или все из них, выполните следующие действия:
First only
:
if (matcher.find()) { // This makes sure that the matcher has found an occurrence before getting a string from it (to avoid exceptions)
occurrence = matcher.group(1);
}
Last only
:
while(matcher.find()) { // This is just a simple while loop which will set 'n' to whatever the next occurrence is, eventually just making 'n' equal to the last occurrence .
occurrence = matcher.group(1);
}
All of them
:
while(matcher.find()) { // Loops every time the matcher has an occurrence , then adds that to the occurrence string.
occurrence += matcher.group(1) + ", "; //Change the ", " to anything that you want to separate the occurrence by.
}
Надеюсь, это помогло вам :)