2010-03-02 2 views
1

정규식 :이 텍스트 줄에이 정규 표현식을 사용할 수 있습니까?

String regexp = "([0-9.]{1,15})[ \t]*([0-9]{1,15})[ \t]*([0-9.]{1,15})[ \t]*(\"(.*?)\"\\s+\\((\\d{4})\\)\\s+\\{(.*?)\\})"; 

텍스트 : 내가 함께 자바와 MySQL을 사용하려고 해요

 
1000000103  50 4.5 #1 Single (2006) 
2...1.2.12  8 2.7 $1,000,000 Chance of a Lifetime (1986) 
11..2.2..2  8 5.0 $100 Taxi Ride (2001) 
....13.311  9 7.1 $100,000 Name That Tune (1984) 
3..21...22  10 4.6 $2 Bill (2002) 
30010....3  18 2.7 $25 Million Dollar Hoax (2004) 
2000010002  111 5.6 $40 a Day (2002) 
2000000..4  26 1.6 $5 Cover (2009) 
.0..2.0122  15 7.8 $9.99 (2003) 
..2...1113  8 7.5 $weepstake$ (1979) 
0000000125 3238 8.7 Allo Allo! (1982) 
1....22.12  8 6.5 Allo Allo! (1982) {A Barrel Full of Airmen (#7.7) 

. 나는 내가 계획하고있는 프로젝트를 위해 그것을 배우고있다. 원하는 출력을 다음과 같이 지정하십시오.

distribution = first column 
rank = second column 
votes = thirst column 
title = fourth column 

첫 번째 세 가지가 정상적으로 작동합니다. 네 번째 문제가 생깁니다.

잘 안되는 것은 중괄호로 시작하는 것입니다. 처음 몇 개의 항목을 아예 붙여 넣으면 몇 가지 더 쉽게 보여줄 수 있습니다. 그래서 여기 그들은 없습니다 : 내가 사용하고

 
0...001122  16 7.8 "'Allo 'Allo!" (1982) {Gruber Does Some Mincing (#3.2)} 
100..01103  21 7.4 "'Allo 'Allo!" (1982) {Hans Goes Over the Top (#4.1)} 
....022100  11 6.9 "'Allo 'Allo!" (1982) {Hello Hans (#7.4)} 
0....03022  21 8.4 "'Allo 'Allo!" (1982) {Herr Flick's Revenge (#2.6)} 
......8..1  6 7.0 "'Allo 'Allo!" (1982) {Hitler's Last Heil (#8.3)} 
.....442..  5 6.5 "'Allo 'Allo!" (1982) {Intelligence Officers (#6.5)} 
....1123.2  9 6.9 "'Allo 'Allo!" (1982) {It's Raining Italians (#6.2)} 
....1.33.3  10 7.8 "'Allo 'Allo!" (1982) {Leclerc Against the Wall (#5.18)} 
....22211.  8 6.4 "'Allo 'Allo!" (1982) {Lines of Communication (#7.5)} 

코드 :

stmt.executeUpdate("CREATE TABLE mytable(distribution char(20)," + 
     "votes integer," + "rank float," + "title char(250));"); 
    String regexp ="([\\d\\.]+)\\s+(\\d+)\\s+([\\d\\.]+)\\s+(.*?\\s+\\(\\d{4}\\).*)"; 
    Pattern pattern = Pattern.compile(regexp); 
    String line; 
    String data= ""; 
    while ((line = bf.readLine()) != null) { 
    data = line.replaceAll("'", " "); 
    String data2 = data.replaceAll("\"", ""); 
    //System.out.println(data2); 
    Matcher matcher = pattern.matcher(data2); 
    if (matcher.find()) { 
     String distribution = matcher.group(1); 
     String votes = matcher.group(2); 
     String rank = matcher.group(3); 
     String title = matcher.group(4); 
     //System.out.println(distribution + " " + votes + " " + rank + " " + title); 
     String todo = ("INSERT into mytable " + 
      "(Distribution, Votes, Rank, Title) "+ 
      "values ('"+distribution+"', '"+votes+"', '"+rank+"', '"+title+"')"); 
     stmt = con.createStatement(); 
     int r = stmt.executeUpdate(todo); 
    } 
    } 
+0

아마도 "work"는 "예제 입력의 각 줄마다 원하는 부분 문자열을 캡처합니다"를 의미합니다.이 부분은 테스트 할 수 있습니다. 특히 원하는 결과가 무엇인지 확실하지 않기 때문에 특히 그렇습니다. 숙제 일 수는 없지, 그렇지? – Cascabel

+0

"Allo 'Allo"제목 검색 결과는 이어야합니다. 제목 = Allo Allo! (1982) {Lines of Communication (# 7.5)} –

+0

무엇을 찾으려고합니까? – jasonbar

답변

0

없음은하지 않을 것입니다.

  1. [ \t]이 될 것 [ \t]+ 또는 \s+; 당신의 숫자는 오른쪽 정렬 공간을 사용 (탭 외에있는 경우) 샘플 입력에서
  2. 백 슬래시는 당신이 "'Allo 'Allo" 될위한 타이틀 결과를 원하는 점을 감안 문자열 리터럴

내부에 이중 이스케이프해야합니다입니다 Title = Allo Allo! (1982) {Lines of Communication (#7.5)} 시도 :

pattern = "([0-9\\.]+)[ \\t]+([0-9]+)[ \\t]+([0-9\\.]+)[ \\t]+(.*?[ \\t]+\\([0-9]{4}\\).*)"; 

또는 (Fadrian 같은 간단한 제안) :

pattern = "([\\d\\.]+)\\s+(\\d+)\\s+([\\d\\.]+)\\s+(.*?\\s+\\(\\d{4}\\).*)"; 

더 읽기 아부 t Backslashes, escapes, and quoting을 입력하고 Pattern javadoc 페이지 이름을 사용하십시오.

+0

그래, 내가 나쁜 것을 알고있다. 따옴표를 붙이지 만 텍스트 파일을 제거했다. 큰 따옴표를 사용하면 동등하지 않으므로 부적절하게 배치된다. "안녕하세요"안녕하세요. " –

+0

여기 코드가 잘못되었습니다. 위로 가기 –

0

이것은 \ *이

([\d\.]*)\s*([\d\.]*)\s*([\d\.]*)\s*(.*)\s* 
이야 당신은 당신이 다음뿐만 아니라 줄 끝에 공백에 대한 수용해야하는 경우

([\d\.]*)\s*([\d\.]*)\s*([\d\.]*)\s*(.*) 

를 수행 할 작업을 할 수있는 훨씬 간단 정규식

는 그냥 \ 대신 S의 사용 적은 실수를 정정

+0

이 부분은 정규 표현식의 일부로, 그 밖의 다른 부분은 없습니다. –

+0

이것은 모두를위한 것입니다. 네 개의 열을 추출 할 네 부분 (그룹)이 있습니다. 시도해보십시오 –

+0

아니요 미안 해요 –

3
/Allo Allo! \(1982\) \{A Barrel Full of Airmen \(\#7\.7\)\}/ 
+0

잘 거기에 7000 라인처럼하지만이 형식으로 –

+2

어떤 형식? 너는 아무런 모범을 보이지 않았다. – harschware

+1

+1 내가하려고했던 일을 정확하게 수행했습니다. – polygenelubricants

0

아마 [\의 D.] : 0

회원님이 그래서 이것은 좀 더 나은 정보를 제공해야 더 나은 도움을 위해 ...

추측된다 달성하기 위해 노력하고 무엇인지 : 좀 더 예를 들어 라인, 이것이 어떤 종류의 데이터를 수행 당신은 단지 일치를 원하거나 특정 캡처 그룹을 원합니까?

1

# 1 프로그래밍 규칙을 기억하십시오. 간단하게하십시오! 왜 모든 것을 위해 정규식이 정말로 필요한가요?

당신이 멋지게 정의 된 표 형식을 가지고있는 것처럼 보입니다 ... tsv에 있습니까?

그렇지 않으면 처음부터 3 열의 공백을 기준으로 한 줄 단위로 읽을 수 있으며 마지막 열만 구문 분석 할 정규식이 필요합니다.

+0

umm 어떻게 해야할지 잘 모르겠 음 –

2

대신 split을 사용할 수 있으며 탭으로 분할 했습니까? 또는 opencsv library을 가져 와서 사용하십시오.

아마도

.... 

String[] temp; 
String the_line; 
BufferedReader in = new BufferedReader(new FileReader("file.txt")); 

while ((the_line = in.readLine()) != null) 
{ 
    temp = the_line.split("\t"); 
    .... 
} 

.... 
+0

umm 어떻게 해야할지 모르겠다. –

+0

괜찮은 것 같은데,하지만 내가 변수를 데이터베이스에 삽입 할 수 있도록 변수가 필요하다. 크기가 20Mb 인 이유는 무엇인가? 나는 정규 표현식 함수가 더 쉬울 것이라고 생각했다. –

+0

@angad Soni :'temp'는 열의 배열이 될까요? 변수에 할당하거나 배열 요소를 직접 사용 하시겠습니까? – jasonbar

1

같은 세 번째 그룹은 하나의 자리 A는 가정이

 BufferedReader reader = new BufferedReader(new FileReader("yourFile")); 

     Pattern p = Pattern.compile("([0-9\\.]+)[\\s]+([0-9]+)[\\s]+([0-9]\\.[0-9])[\\s]+([^\\s].*$)"); 

     String line; 
     while((line = reader.readLine()) != null) { 
      Matcher m = p.matcher(line); 
      if (m.matches()) { 
       System.out.println(m.group(1)); 
       System.out.println(m.group(2)); 
       System.out.println(m.group(3)); 
       System.out.println(m.group(4)); 
      } 

     } 

을보십시오. 한 자리 숫자 만

+0

그래, 내가 그걸 시도 해왔다.하지만 웬일인지 작동하지 않을 때 나는 에러가 난다. –

+0

당신이 제공 한 동일한 정규 표현식이 아닙니다 파일이 나와 함께 작동합니다 – Lombo

+0

파일을 어떻게 저장 했습니까? 어떤 형식인지 .txt 또는 무엇을 의미합니까? –

0

텍스트를 구문 분석하기 위해 정규식을 사용하지 마십시오. 정규 표현식은 텍스트의 패턴을 일치시키고 부품/구성 요소의 텍스트를 구문 분석하지 않습니다. 귀하의 질문에 텍스트 파일의 예는 실제변경 예 인 경우

다음, "파서"그냥 보너스로 (작동해야 기본 킥오프 예를 들어 다음, 그것은 또한 즉시 필요한 JDBC 코드를 실행). 귀하의 데이터를 변경하지 않고 c:\test.txt으로 복사했습니다.

public static void main(String... args) throws Exception { 
    final String SQL = "INSERT INTO movie (distribution, votes, rank, title) VALUES (?, ?, ?, ?)"; 
    Connection connection = null; 
    PreparedStatement statement = null; 
    BufferedReader reader = null;   

    try { 
     connection = database.getConnection(); 
     statement = connection.prepareStatement(SQL); 
     reader = new BufferedReader(new InputStreamReader(new FileInputStream("/test.txt"))); 

     // Loop through file. 
     for (String line; (line = reader.readLine()) != null;) { 
      if (line.isEmpty()) continue; // I am not sure if those odd empty lines belongs in your file, else this if-check can be removed. 

      // Gather data from lines. 
      String distribution = line.substring(0, 10); 
      int votes = Integer.parseInt(line.substring(12, 18).trim()); 
      double rank = Double.parseDouble(line.substring(20, 24).trim()); 
      String title = line.substring(26).trim().replace("\"", ""); // You also want to get rid of those double quotes, huh? I am however not sure why, maybe you initially had problems with it in your non-prepared SQL string... 

      // Just to show what you've gathered. 
      System.out.printf("%s, %5d, %.1f, %s%n", distribution, votes, rank, title); 

      // Now add batch to statement. 
      statement.setString(1, distribution); 
      statement.setInt(2, votes); 
      statement.setDouble(3, rank); 
      statement.setString(4, title); 
      statement.addBatch(); 
     } 

     // Execute batch insert! 
     statement.executeBatch(); 
    } finally { 
     // Gently close expensive resources, you don't want to leak them! 
     if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {} 
     if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {} 
     if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {} 
    } 
} 

참조하십시오. 복잡해진 정규식이 필요 없습니다.

+0

확실히 그 공백을 계산합니다 ... 탭이 있으면 어쩌지 않아도 될까요? 죄송합니다. – vladr

+0

집계 되셨습니까? 나는 당신이 평상시에 무엇을하는지/사용하는지 모르지만, 내 texteditor는 상태 표시 줄에 커서의 열 색인만을 보여줍니다. 탭에 관해서는, 나는 데이터가 OP와 똑같이 복제된다는 말로 이미 자신을 보호했다. 똑똑한 사람을 위해 놀고 싶다면 다른 사람을 찾으십시오. – BalusC

관련 문제