Java 提取字符串中的项
我想在一个特定的字符串中提取Hello world当前我得到的第一个和最后一个事件。在一个字符串中有3(三)个Hello world文本,我想在每个特定的字符串中提取它们Java 提取字符串中的项,java,string,indexing,substring,Java,String,Indexing,Substring,我想在一个特定的字符串中提取Hello world当前我得到的第一个和最后一个事件。在一个字符串中有3(三)个Hello world文本,我想在每个特定的字符串中提取它们 String text="hellogfddfdfsdsworldhelloasaasasdasdggworldfdfdsdhellodasasddworld"; int x=text.indexOf("hello"); int y=text.indexOf("world"); String test=text.substri
String text="hellogfddfdfsdsworldhelloasaasasdasdggworldfdfdsdhellodasasddworld";
int x=text.indexOf("hello");
int y=text.indexOf("world");
String test=text.substring(x, y+4);
System.out.println(test);
x=text.indexOf("hello");
y=text.indexOf("world");
String test1=text.substring(x,y);
System.out.println(test1);
x=text.lastIndexOf("hello");
y=text.lastIndexOf("world);
String test2=text.substring(x, y);
System.out.println(test2);
听起来像是正则表达式的工作。最简单的是
List<String> matchList = new ArrayList<String>();
Pattern regex = Pattern.compile(
"hello # Match 'hello'\n" +
".*? # Match 0 or more characters (any characters), as few as possible\n" +
"world # Match 'world'",
Pattern.COMMENTS);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}
请注意,如果模式可以嵌套,即。e
hello foo hello bar world baz world
不是真正的专家,但我认为regex
可以满足您的需求!
Pattern regex = Pattern.compile(
"hello # Match 'hello'\n" +
"(.*?) # Match 0 or more characters (any characters), as few as possible\n" +
"world # Match 'world'",
Pattern.COMMENTS);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group(1));
}