2014-04-28 5 views
1

오늘 밤 저는 파일에서 단어를 구문 분석하려고 시도하고 있습니다. 공백뿐만 아니라 대문자와 소문자 단어를 보존하면서 모든 구두점을 제거하고 싶습니다.구두점을 제거하고 글자와 공백을 보존하십시오 - Java Regex

String alpha = word.replaceAll("[^a-zA-Z]", ""); 

공백을 포함하여 모든 것을 바꿉니다.

Testing, testing, 1, one, 2, two, 3, three. 포함 된 텍스트 파일을 조작, 출력은 내가 출력은 변경되지 않습니다

String alpha = word.replaceAll("[^a-zA-Z\\s]", ""); 

로 변경할 때, 그러나 TESTINGTESTINGONETWOTHREE 된다.

여기 전체에서이 코드입니다 : 읽기,

public class UpperCaseScanner { 

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

     //First, define the filepath the program will look for. 
     String filename = "file.txt"; //Filename 
     String targetFile = "";   
     String workingDir = System.getProperty("user.dir"); 

     targetFile = workingDir + File.separator + filename; //Full filepath. 

     //System.out.println(targetFile); //Debug code, prints the filepath. 

     Scanner fileScan = new Scanner(new File(targetFile)); 

     while(fileScan.hasNext()){ 
      String word = fileScan.next(); 
      //Replace non-alphabet characters with empty char. 
      String alpha = word.replaceAll("[^a-zA-Z\\s]", ""); 
      System.out.print(alpha.toUpperCase()); 
     } 

     fileScan.close(); 

    } 
} 

file.txt를 가지고 한 줄 Testing, testing, 1, one, 2, two, 3, three. 내 목표 출력 Testing Testing One Two Three 난 그냥 정규 표현식에서 뭔가 잘못하고 있습니까 읽을 수있다, 아니면 제가해야 할 일이 있습니까? 관련성이있는 경우 32 비트 Eclipse 2.0.2.2에서 작업하고 있습니다.

답변

2

나는 이것을 사용하여 찾고자하는 출력을 얻을 수있었습니다. 여러 공백을 하나의 공백으로 변환해야하는 이유는 확실하지 않았습니다. 그래서 두 번째 공백을 여러 공백을 단일 공백으로 바꾸기 위해 두 번째 호출을 추가했습니다.

public class RemovePunctuation { 
    public static void main(String[] args) { 
     String input = "Testing, testing, 1, one, 2, two, 3, three."; 
     String alpha = input.replaceAll("[^a-zA-Z\\s]", "").replaceAll("\\s+", " "); 
     System.out.println(alpha); 
    } 
} 

이 방법 출력 :

Testing testing one two three

당신이 (당신이 당신의 질문에 보였다처럼) 각 단어의 첫 문자를 대문자로 원하는 경우에 당신이 할 수 있습니다 :

public class Foo { 
    public static void main(String[] args) { 
     String input = "Testing, testing, 1, one, 2, two, 3, three."; 
     String alpha = input.replaceAll("[^a-zA-Z\\s]", "").replaceAll("\\s+", " "); 
     System.out.println(alpha); 

     StringBuilder upperCaseWords = new StringBuilder(); 
     String[] words = alpha.split("\\s"); 

     for(String word : words) { 
      String upperCase = Character.toUpperCase(word.charAt(0)) + word.substring(1) + " "; 
      upperCaseWords.append(upperCase); 
     } 
     System.out.println(upperCaseWords.toString()); 
    } 
} 

출력 :

Testing testing one two three Testing Testing One Two Three

+0

감사합니다 모든 문장 부호를 제거

\p{Punct} 

를 지원하는지 생각합니다. 이 코드는 대문자 단어 만 다루는 단어 색인 프로그램의 일부가 될 것이므로이 후에 어쨌든 문자열은 toUpperCase()를 통해 전달됩니다. 실제로 코드를 통해 출력을 재현 할 수는 없습니다. 전체 코드를 원래 질문으로 편집합니다. – alldavidsluck

+0

내 코드를 질문에 편집했습니다. 직접 정의 된 문자열을 사용하여 조각을 가져올 수 있었지만 문자열이 파일에서 나온다면 나는 이상하게 느껴지지 않습니다. – alldavidsluck

0

내가 자바는이 투입 시간에 대한

+1

이것을 사용하면 공백도 제거됩니다. 필자는 테스트 파일에 공백이 하나 밖에 없기 때문에 생각합니다. – alldavidsluck

3
System.out.println(str.replaceAll("\\p{P}", ""));   //Removes Special characters only 
System.out.println(str.replaceAll("[^a-zA-Z]", ""));  //Removes space, Special Characters and digits 
System.out.println(str.replaceAll("[^a-zA-Z\\s]", "")); //Removes Special Characters and Digits 
System.out.println(str.replaceAll("\\s+", ""));   //Remove spaces only 
System.out.println(str.replaceAll("\\p{Punct}", ""));  //Removes Special characters only 
System.out.println(str.replaceAll("\\W", ""));   //Removes space, Special Characters but not digits 
System.out.println(str.replaceAll("\\p{Punct}+", "")); //Removes Special characters only 
System.out.println(str.replaceAll("\\p{Punct}|\\d", "")); //Removes Special Characters and Digits