0

I can replace (.*) with \1 in notepad++ for e.g. string

aaa hello how are u bbb

if i do below in notepad ++ it works

find : aaa(.*)bbb
replace: ccc \1

output: ccc hello how are u 

How to do similar in JAVA , i can match pattern using str.matches but how to replace it as above

2

1 Answer 1

0

Easy way, using replaceAll and $1 for first group

text.replaceAll("aaa(.*)bbb", "$1"); 
// or
text.replaceAll("^aaa(.*)bbb$", "$1");  // match whole input string below

replaceAll searches all matches of first argument as regular expression and replaces it with second argument. Dollar in second argument are used to captures sequences (groups). To just replace once1, use replaceFirst().

Similar can be done with a Matcher:

Matcher matcher = Pattern.compile("aaa(.*)bbb").matcher(text);
matcher.replaceAll("$1");

Note 1: since using (.*), the pattern will be found at most once - .* tries to match as much as possible. Example: if text = "aaa first bbb and aaa second bbb" the group in aaa(.*)bbb will match " first bbb and aaa second " - the largest sub-sequence between aaa and bbb. This can be prevented using (.*?) (reluctant quantifier) that tries to match the smallest sub-sequence possible.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.