Reputation: 336
I have a string in java which contains text as
Hello user your choice is in (1,2,3,4) as selected by you.
Now I want to remove choice is in (1,2,3,4)
from this string with ""
.
I cannot directly do it using replace()
in java as data inside the ()
is dynamic and changes every time.
Output required
Hello user your as selected by you.
I tried using regex but it failed and did not work, my regex
(?s)(\\choice is in .*?\\\\(\\\\)
Upvotes: 1
Views: 126
Reputation: 79245
Given below is a non-regex solution:
public class Main {
public static void main(String[] args) {
String s = "Hello user your choice is in (1,2,3,4) as selected by you.";
int start = s.indexOf(" choice is in (");
int end = s.indexOf(")", start);// Index of `)` after the index, `start`
s = s.substring(0, start) + s.substring(end + 1);
System.out.println(s);
}
}
Output:
Hello user your as selected by you.
Upvotes: 2
Reputation: 11
Please refer below code.
String pattern = "choice is in (.*?) ";
String userString = "Hello user your choice is in (1,2,3,4) as selected by you";
userString = userString.replaceAll(pattern, "");
System.out.println(userString);
Output will be : Hello user your as selected by you
Upvotes: 1
Reputation: 1764
Try This:
String pattern = "choice is in (.*) as";
String userString = "Hello user your choice is in (1,2,3,4) as selected by you";
userString = userString.replaceAll(pattern, "as");
System.out.println(userString);
And the output would be:
Hello user your as selected by you
Upvotes: -1
Reputation: 627056
You may use
.replaceAll("\\s+choice\\s+is\\s+in\\s+\\([^()]*\\)", "")
See the regex demo.
\s+
- 1+ whitespaceschoice\s+is\s+in
- choice is in
with any 1+ whitespaces in between words\s+
- 1+ whitespaces\([^()]*\)
- a (
, then any 0+ chars other than (
and )
and then a )
See Java demo:
String s = "Hello user your choice is in (1,2,3,4) as selected by you.";
System.out.println(s.replaceAll("\\s+choice\\s+is\\s+in\\s+\\([^()]*\\)", ""));
// => Hello user your as selected by you.
Upvotes: 2