For example, I have front boundary 'x' and back boundary 'y'
EG Given a string 'abcxfoobaryblablah', it should return 'foobar'.
Assume the two boundaries only appear exactly once in the string like in the example.
Thanks! Doesn't have to use Regex, but I guess that's the best method.
String s = "abcxfoobaryblablah";
s = s.substring(s.indexOf('x') + 1, s.indexOf('y'));
System.out.println(s);
Out
foobar
May be a long code but just a simple logic.
String str="abcxfoobaryblablah";
char array[]=str.toCharArray();
boolean flag=false;
String answer="";
for(int i=0;i<array.length;i++)
{
if(array[i]=='x'){
flag=true;
continue;
}
if(array[i]=='y') break;
if(flag)answer+=array[i];
}
System.out.println(answer);
String input = "abcxfoobaryblablah";
int startIndex = input.indexOf("x");
int endIndex = input.indexOf("y");
String output = input.substring(startIndex+1, endIndex);
System.out.println(output);
You could certainly do substrings, but it is possible with regex.
String str = "abcxfoobaryblablah";
str = str.replaceAll("^.*x|y.*$", "");
^.*x
matches the characters from the start of the String
up to x
. y.*$
matches the characters from y
to the end of the String
.
Note that if x
is after y
, then this will keep just the characters after x
to the end of the String
. If x
is not present, it will keep the characters from the start of the String
to y
. If you only want it to work when both x
and y
are in there in the correct order, then this is what you want:
String str = "abcxfoobaryblablah";
str = str.replaceAll("^.*x(.*)y.*$", "$1");
This uses groups .
最简单的方法是:
String middle = str.replaceAll(".*x(.*)y.*", "$1");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.