Replace a line by excluding some lines in Java

How to replace the following line in Java:

Sports videos (From 2002 To 2003) here. 

FROM

 Sports videos 2002 2003 here. 

I have a usage code, but it deletes the entire line, i.e.
I get this conclusion: 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

VARIOUS LINE WITH DATE FORMAT

If the above line has a date format, for example ( \\ ) or any other character / words, then a digit, the answer will not work

I am replacing the original answer with this template and it will work

 String pattern= "\\((From)(.*)(To)(.*)\\)"; 
+4
source share
1 answer

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 over the years. This is used to not remember these groups.

Second

You do not use group identifiers, for example, $ 1, $ 2. I fixed the use of $ 2 and $ 4 for the 2nd 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"); 
+3
source

All Articles