简体   繁体   English

如何在Java中使用正则表达式删除字符串的一部分

[英]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);           
}

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

您可以尝试以下方法:

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

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. 我认为第二种解决方案更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM