从其他字符串中提取特定字符串
Extract certain string from other string
我自己做了一个项目,我需要提取URL的某个字符串。
在我使用之前
Arrays.asList(URL.split("/")).get(6);
但是如果是在第 6 个 / 之后,我只能得到它。
我知道 matcher() 有一些东西,但我没有让它工作。
例如:
https://www.amazon.de/gp/product/SOMETEXTHERE/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1
我想提取出SOMETEXTHERE。但是这个角色在变化,所以我不能说它总是一样的。
然后我需要一个单独的字符串中的 SOMETEXT。
使用 group(1)
检索 product/
和 /ref
之间的文本:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile(".*product/(.*)/ref.*");
Matcher matcher = pattern.matcher("https://www.amazon.de/gp/product/SOMETEXTHERE/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1");
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
}
}
我自己做了一个项目,我需要提取URL的某个字符串。 在我使用之前
Arrays.asList(URL.split("/")).get(6);
但是如果是在第 6 个 / 之后,我只能得到它。 我知道 matcher() 有一些东西,但我没有让它工作。
例如:
https://www.amazon.de/gp/product/SOMETEXTHERE/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1
我想提取出SOMETEXTHERE。但是这个角色在变化,所以我不能说它总是一样的。 然后我需要一个单独的字符串中的 SOMETEXT。
使用 group(1)
检索 product/
和 /ref
之间的文本:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile(".*product/(.*)/ref.*");
Matcher matcher = pattern.matcher("https://www.amazon.de/gp/product/SOMETEXTHERE/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1");
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
}
}