tags:

views:

75

answers:

1

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)(.*)\\)";
+3  A: 

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