2013-05-06 2 views
-2

현재 특정 문자열 안에 Hello world를 추출하고 싶습니다. 현재 처음 및 마지막 Occurences.there에 문자열이 있습니다. 각 특정 문자열에 문자열이 3 개 있습니다.문자열 내에서 항목 추출

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); 
+0

전문가는 아니지만 '정규식'이 사용자의 필요를 충족시킬 수 있다고 생각합니다! – SudoRahul

답변

0

정규 표현식 작업과 비슷합니다. 가장 간단한 일 경우에만 텍스트를helloworld 사이 을 원하는 경우에,

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()); 
} 

수, 패턴이 중첩 될 수 있다면이 실패 난을

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)); 
} 

주를 사용합니다. 이자형. hello foo hello bar world baz world.

+0

감사합니다. – mgk22