2016-03-18 28 views
1

我正在編寫一個小程序,修剪文件名中某個字符後面的所有內容。這個字符是由用戶指定的,我希望我的部分正則表達式能夠適應這一點。我的計劃是在正則表達式查詢中使用佔位符,但我遇到了一些麻煩,無法找到有關它的更多信息。 這是我到目前爲止的代碼:Java:在正則表達式查詢中使用佔位符

//get all files (variablepath is a String passed to the method, so is altSep) 
File dir = new File(path); 
File[] listOfFiles = dir.listFiles(); 

String regex = "[\\%s\\(\\)]+[\\w\\s]+"; 
regex = String.format(regex, altSep); 

for (File i : listOfFiles) { 
    String currName = i.getName(); 
    String newName = currName.replaceAll(regex, ""); 
    newName = path + '\\' + newName; 
    File newFile = new File(newName); 
    i.renameTo(newFile); 
} 

是的,它的工作原理也刪除後方的空間的一切。我還擔心%s可能與用戶可能輸入的其他字符相匹配。在正則表達式中使用佔位符是一個好主意? (並且我還在學習Java,所以你可能會發現其他一些可以更容易解決的問題)

Sidenotes:該字符本身也必須被刪除,因爲這涉及到文件名,所以擴展必須保持完整。

+3

爲什麼不'String newName = currName.substring(0,currName.indexOf(character)+1)'? – Grogi

+0

@Grogi注意到,如果Java版本<1.7,子字符串可能有內存泄漏問題 – Kent

+0

@Grogi我意識到我沒有足夠詳細描述這個問題。你的解決方案很好,但我也需要擺脫給定的角色本身。我編輯了我的問題。 – Iarwain

回答

1

EDIT2您沒有發佈您用於獲取用戶輸入的類。我覺得這是問題發生的地方。我想你的正則表達式與的BufferedReaderInputStreamReader的類,輸出是罰款:

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.regex.*; 
import java.io.BufferedReader; 
import java.io.InputStreamReader; 

public static void main(String[] args) throws IOException { 

    BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); 
    # get filename from user 
    System.out.println("Enter a filename: "); 
    String currName = buffer.readLine(); 

    # get altSep from user 
    System.out.println("Enter a altSep: "); 
    String altSep = buffer.readLine(); //reader.next(); 
    altSep = altSep.matches("[0-9a-zA-Z]") ? altSep : "\\" + altSep; 

    # format regex with user input 
    String regex = "(%s.*)(?=\\.\\w+)"; 
    regex = String.format(regex, altSep);   
    String newName = currName.replaceAll(regex, ""); 

    # the output 
    System.out.println(newName); 

} 

輸出:

Enter a filename: 
MRS (A\ TP)1(6R)-01.fa 
Enter a altSep: 
(
MRS .fa 

MRS (A\ TP)1(6R)-01.fa 
Enter a altSep: 
\ 
MRS (A.fa 

MRS (A\ TP)1(6R)-01.fa 
Enter a altSep: 
6 
MRS (A\ TP)1(.fa 

MRS (A\ TP)1(6R)-01.fa 
Enter a altSep: 
P 
MRS (A\ T.fa 

MRS (A\ TP)1("6R")-01.fa 
Enter a altSep: 
" 
MRS (A\ TP)1(.fa 
+0

對不起,我對你的答案進行了編輯。這個答案(尤其是評論('(%s。*)(?= \\。\\ w +)')中的正則表達式有所幫助,但我發現它不能接受所有字符作爲輸入(如(字符) 。我還編輯了我的問題,所以你可以看到輸入來自 – Iarwain

+0

@TomKral:來自注釋的正則表達式不能輸入像'('字符的原因是,正則表達式被弄糊塗是否它是一個文字(或捕獲組開始。所以,我添加了一行,以根據輸入(altSep)檢查是否需要轉義'\\'。請嘗試看看它是否符合您的需求。 – Quinn

+0

它現在有效。非常感謝! – Iarwain

0

嘗試從 改變正則表達式 [\\%S \\( \\)] + [\\ w \\ s] + 至 [\\\\%s \\(\\)] + [\\ w \\ s] +

問題是反斜槓是Java字符串文字和正則表達式中的轉義字符。所以當你使用字符串文字來表示一個正則表達式時,有兩組轉義要考慮。如果用戶輸入轉義字符作爲輸入,則生成的正則表達式可能不是所需的正則表達式,並且可能不會給出所需的輸出。