Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Text between special characters and replace string

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**
like image 619
Roadman1991 Avatar asked Apr 16 '26 19:04

Roadman1991


2 Answers

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

like image 53
MaxZoom Avatar answered Apr 18 '26 07:04

MaxZoom


You just need to extend boundaries:

s = s.substring(s.indexOf("*"));
s = s.substring(0, s.indexOf("*", 1)+1);
like image 33
Andremoniy Avatar answered Apr 18 '26 07:04

Andremoniy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!