2017-02-19 1 views
3

문자열에서 데이터를 분리하는 방법은 여기에서 읽었습니다. 대부분의 경우 놀라운 결과를 냈습니다.문자열에서 데이터 나누기

공백, 사용자 이름, MD5 해시, "에 둘러싸인 일반 텍스트 암호"로 구분 된 줄에 네 개의 섹션이있는 자격 증명 파일에서 데이터를 가져 오려고합니다. 마지막으로 역할이 있습니다. .split을 사용하여 내가 필요로하는 것이라고 생각하기 시작했지만, 세 번째 또는 두 번째 항목에는 가끔씩 분할을 필터링해야하는 공간이 있습니다. 어떤 아이디어?

credentialLine에서 분리됩니다 라인 :

griffin.keyes 108de81c31bf9c622f76876b74e9285f "알파벳 수프"사육사

FileInputStream credentialsFile = null; 
    Scanner inFS = null; 
    String credFile = ".\\src\\authenticationsystem\\credentials.txt"; 

    System.out.println("\nOpening file credentials.txt"); 

    credentialsFile = new FileInputStream(credFile); 
    inFS = new Scanner(credentialsFile); 
    String credentialLine = inFS.nextLine(); 
    System.out.println(credentialLine); 
    System.out.println("Closing file credentials.txt\n"); 
    credentialsFile.close(); 

    String[] userCreds = credentialLine.split("\\s+"); 
    String userCred = userCreds[0]; 
    String userMD = userCreds[1]; 
    String userPass = userCreds[2]; 
    String userRole = userCreds[3]; 

답변

2

일부 공백을 무시하는 정규식을 사용해야합니다. 제공 한 예에서 무시할 공간이 따옴표 안에있는 것 같습니다.

즉이 같은 것을 사용할 수있는 모든 값의 경우 경우 :

String[] userCreds = credentialLine.split("((?!\"[^\" ]+)\\s+(?![^ \"]+\"))"); 

((?!\"[^\" ]+) 의미하십시오 문자의 순서에 의해 fallowed 따옴표 (다른 후 공백이나 인용이 있지 않은지 확인) 앞뒤로 하나 또는 여러 공백.

+0

이 문서에서 너무 빨리 다루지 마십시오. 일반 텍스트 암호에 ** 공백이없는 경우 ** 실패합니다. 어쨌든 거기에는 공간이있을 때만 있습니다. – DevilsHnd

+0

authenticationsystem.AuthenticationSystem.main (AuthenticationSystem.java:48) C : \ Users \ Anna \ AppData \ Local \ NetBeans \ Cache \ 8.2에있는 3 \t 스레드 "main"아래 예외가 받았습니다. \ executor-snippets \ run.xml : 53 : Java가 반환되었습니다 : 1 BUILD FAILED (총 시간 : 2 초) – Ghostey

+0

@DevilsHnd 네 말이 맞아, 나는 그것을 고려하지 않았다. – Titus

0
String stringToSearch = "griffin.keyes 108de81c31bf9c622f76876b74e9285f \"alphabet soup\" zookeeper"; 

Pattern p1 = Pattern.compile("(?:[^\" ]+|\"[^\"]+\")+"); 
Matcher m = p1.matcher(stringToSearch); 
while (m.find()) 
{ 
    System.out.println(m.group()); 
} 

When it encounters qutoes, the group alternates to the right hand side, which matches everything between the quotes, and returns to the left hand side for matching everything up to the next space.