4

How can I replace following string in Java:

Sports videos (From 2002 To 2003) here.

TO

Sports videos 2002 2003 here.

I have use code but it remove the whole string i.e.
I am getting this ouput: Sports videos here.

String pattern= "\\((From)(?:\\s*\\d*\\s*)(To)(?:\\s*\\d*\\s*)\\)";

String testStr = "Sports videos (From 2002 To 2003) here.";

String testStrAfterRegex =  testStr.replaceFirst(pattern, "");

What is missing here?

Thanks

DIFFERENT STRING WITH DATE FORMATTER

If above string has date formatter like(\\) or any other character/words then digit, the answer will not work

I replace orginal answer with this pattern and it will work

String pattern= "\\((From)(.*)(To)(.*)\\)";

1 Answer 1

3

Change to

    String pattern= "\\((From)(\\s*\\d*\\s*)(To)(\\s*\\d*\\s*)\\)";
    String testStr = "Sports videos (From 2002 To 2003) here.";
    String testStrAfterRegex =  testStr.replaceFirst(pattern, "$2 $4");

There are two problems:

First

You put (?:) in groups with years. This is used to not remember these groups.

Second

You don't use group identifiers, like $1, $2. I fixed using $2 and $4 for 2th and 4th groups.


EDIT

Cleaner solution:

    String pattern= "\\(From(\\s*\\d*\\s*)To(\\s*\\d*\\s*)\\)";
    String testStr = "Sports videos (From 2002 To 2003) here.";
    String testStrAfterRegex =  testStr.replaceFirst(pattern, "$1$2");
Sign up to request clarification or add additional context in comments.

3 Comments

Where I can learn for group identifiers.? Also What about If I want to replace "TO" with - (dash). i.e. Sports videos 2002- 2003 here.
I found myself String testStrAfterRegex = testStr.replaceFirst(pattern, "$2 - $4");
@NETQuestion: Hi, you can learn more here regular-expressions.info/brackets.html

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.