Rakesh
Rakesh

Reputation: 17

How to remove a part of string using regex in java

I am comparing file names in a folder ,I want to remove some part of string and check whether name exists or not

Here is my file name :

file1Name:AB-05012_MM-AB_585859_01 
file2Name:AB-05012_MM-AB_732320_01-1

Now i want to compare the string only till

AB-05012_MM-AB_732320_01 ignore '-1'

Here is my logic

if (file1Name.equals(file2Name.contains(""))){
  list.add(file1Name);           
}

Upvotes: 0

Views: 196

Answers (3)

Kerwin
Kerwin

Reputation: 1212

if your file name is same length:

if (file1Name.equals(file2Name.substring(0,24))){
 //if same to some  task              
}

else:

if (file1Name.equals(file2Name.substring(0,file2Name.lastIndexOf('-')))){
 //if same to some  task              
}

And I think the second solution better.

Upvotes: 0

SacJn
SacJn

Reputation: 777

When you know there is an extra character in second file name then why not using

fileName2.startsWith ( fileName1)

or

int indexOfDot = fileName1.lastIndexOf(".");
fileName2.startsWith ( fileName1.subString( 0, indexOfDot)

But this is very specific to your problem. or for the cases where
fileName2 = fileName1 + any character or digit

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

You can try this:

String myStr = str.substring(0, str.lastIndexOf("-1")); 

Upvotes: 0

Related Questions