For instance I have a String that contains:
String s = "test string *67* **Hi**";
I want to to get this String :
*67*
With the stars, so I can start replace that part of the string. My code at the moment looks like this:
String s = "test string *67* **Hi**";
s = s.substring(s.indexOf("*") + 1);
s = s.substring(0, s.indexOf("*"));
This outputs: 67
without the stars.
I would like to know how to get a string between some special character, but not with the characters together, like I want to.
The output should be as followed:
//output: test string hello **hi**
To replace only the string between special characters :
String regex = "(\\s\\*)([^*]+)(\\*\\s)";
String s = "test string *67* **Hi**";
System.out.println(s.replaceAll(regex,"$1hello$3"));
// output: test string *hello* **Hi**
EDIT
To remove also the special characters use below regex:
String regex = "(\\s)(\\*[^*]+\\*)(\\s)";
You just need to extend boundaries:
s = s.substring(s.indexOf("*"));
s = s.substring(0, s.indexOf("*", 1)+1);
s = s.substring(s.indexOf("*"));
s = s.substring(0, s.indexOf("*", 1) + 1);
Your +1 is in the wrong place :) Then you just need to find the next one starting from the second position
I think you can even get your output with List as well
String s = "test string *67* **Hi**";
List<String> sList = Arrays.asList(s.split(" "));
System.out.println(sarray.get(sarray.indexOf("*67*")));
Hope this will help.
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.