i want extract hello world inside particular string getting first , last occurences.there 3(three) hello world text inside string want them on each particular string.
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);
sounds job regular expression. simplest 1 be
list<string> matchlist = new arraylist<string>(); pattern regex = pattern.compile( "hello # match 'hello'\n" + ".*? # match 0 or more characters (any characters), few possible\n" + "world # match 'world'", pattern.comments); matcher regexmatcher = regex.matcher(subjectstring); while (regexmatcher.find()) { matchlist.add(regexmatcher.group()); }
if want text between hello
, world
, use
pattern regex = pattern.compile( "hello # match 'hello'\n" + "(.*?) # match 0 or more characters (any characters), few possible\n" + "world # match 'world'", pattern.comments); matcher regexmatcher = regex.matcher(subjectstring); while (regexmatcher.find()) { matchlist.add(regexmatcher.group(1)); }
note fails if patterns can nested, i. e. hello foo hello bar world baz world
.
Comments
Post a Comment