java - Separate String into two parts -
my string
looks this: "/namestart blabla1 /nameend blabla2"
. ps. might /namestartblabla1/nameendbababa2
example.
i need 2 strings:
string1 == blabla1 string2 == blabla2
i got strings this:
if(mystring.startswith("/namestart")){ pattern p = pattern.compile("/namestart(.*?)/nameend"); matcher m = p.matcher(mystring); if (m.find()) { string string1 = m.group(1); string string2 = mystring.substring(mystring.indexof("/nameend")+8, mystring.length())); } }
first question can done better or solution ok?
and second problem blabla1 , blabla2 can anything, can /nameend (probaby wont be) or screw reg expression. theoretical solution that?
i not sure trying maybe try using groups
indexes instead of substring
. rid of if(mystring.startswith("/namestart")){
can use ^
anchor @ star of regex indicate matching part should placed @ start of string.
string mystring = "/namestart blabla1 /nameend blabla2"; pattern p = pattern.compile("^(/namestart)(.*?)(/nameend)(.*)"); matcher m = p.matcher(mystring); if (m.find()) { string string1 = m.group(2); string string2 = m.group(4); system.out.println(string1 + "|" + string2); }
output
blabla1 | blabla2
also depending on trying achieve in situation blabla1
or blabla2
/nameend
can try changing (.*?)
(.+?)
.
Comments
Post a Comment