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**
DEMO and Regex explanation
EDIT
To remove also the special characters use below regex:
String regex = "(\\s)(\\*[^*]+\\*)(\\s)";
DEMO
You just need to extend boundaries:
s = s.substring(s.indexOf("*"));
s = s.substring(0, s.indexOf("*", 1)+1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With