3

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**
Roadman1991
  • 169
  • 3
  • 16
  • Careful by replacing a `String` like this. You could replace more than you thought in `"test string *67* **Hi**, I am **67**"`. But since you are already able to find the `String` using `substring`, why not just take the left part, add the replacement part, add the right part. – AxelH Sep 07 '17 at 13:25
  • @Roadman1991 Would you like to replace also string `*Hi*` ? – MaxZoom Sep 07 '17 at 13:48
  • how is this upvoted?... – DPM Sep 07 '17 at 13:54
  • Why you want to use replace ??? what you targeting is to separate the string, in this case I would say going with replace is not preferable. – Simmant Sep 07 '17 at 14:08

4 Answers4

3

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

MaxZoom
  • 7,619
  • 5
  • 28
  • 44
2

You just need to extend boundaries:

s = s.substring(s.indexOf("*"));
s = s.substring(0, s.indexOf("*", 1)+1);
Andremoniy
  • 34,031
  • 20
  • 135
  • 241
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

Mário Fernandes
  • 1,822
  • 1
  • 21
  • 21
0

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.

Simmant
  • 1,477
  • 25
  • 39