2010-03-09 2 views
0

에 텍스트를 분할하고 나는 그것이 내가로 할 수 있습니다 원하는 :정규식이 잘 텍스트 파일 그것의 일부 6 열

Column 1 = distribution 
Column 2 = votes 
Column 3 = rank 
Column 4 = title 
Column 5 = year 
Column 6 = Subtitle (but only where there is a subtitle) 

정규식 내가 사용하는 것입니다 :

사용

그러나 당신이 내가 그것을 해결할 수 있습니다 방법에 대한 아이디어를 작동하지 않는 것 말할 수

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

1000000103  50 4.5 #1 Single (2006) {THis would be a subtitle example} 
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) 

CODE IM :

try { 
     FileInputStream file_stream = new FileInputStream("/Users/angadsoni/Desktop/ratings-1.txt"); 
     DataInputStream data_stream = new DataInputStream(file_stream); 
     BufferedReader bf = new BufferedReader(new InputStreamReader(data_stream)); 
     ResultSet rs; 
     Statement stmt; 
     Connection con = null; 
     Class.forName("org.gjt.mm.mysql.Driver").newInstance(); 
     String url = "jdbc:mysql://localhost/mynewdatabase"; 
     con = DriverManager.getConnection(url,"root",""); 
     stmt = con.createStatement(); 
    try{ 
    stmt.executeUpdate("DROP TABLE myTable"); 
    }catch(Exception e){ 
    System.out.print(e); 
    System.out.println("No existing table to delete"); 

    //Create a table in the database named mytable 
    stmt.executeUpdate("CREATE TABLE mytable(distribution char(20)," + "votes integer," + "rank float," + "title char(250)," + "year integer," + "sub char(250));"); 
String rege= "^([\\d.]+)\\s+(\\d+)\\s+([\\d.]+)\\s+(.+?)\\s+\\((\\d+)\\)(?:\\s+\\{([^{}]+))?"; 
    Pattern pattern = Pattern.compile(rege); 
    String line; 
    String data= ""; 
    while ((line = bf.readLine()) != null) { 
    data = line.replaceAll("'", ""); 

Matcher matcher = pattern.matcher (data);

if (matcher.find()) { 
     System.out.println("hello"); 
     String distribution = matcher.group(1); 
     String votes = matcher.group(2); 
     String rank = matcher.group(3); 
     String title = matcher.group(4); 
     String year = matcher.group(5); 
     String sub = matcher.start(6) != -1 ? matcher.group(6) : ""; 
     System.out.printf("%s %8s %6s%n%s (%s) %s%n%n", 
     matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4), matcher.group(5), 
     matcher.start(6) != -1 ? matcher.group(6) : ""); 
     String todo = ("INSERT into mytable " + 
      "(Distribution, Votes, Rank, Title, Year, Sub) "+ 
      "values ('"+distribution+"', '"+votes+"', '"+rank+"', '"+title+"', '"+year+", '"+sub+"');"); 
     int r = stmt.executeUpdate(todo); 
    }//end if statement 
    }//end while loop 
} 
+0

음, 4 개의 다른 열로 나눠서 배포, 투표, 순위, 제목과 같이 나눠서 제목이 3 부분으로 나뉘어서 연도에 따라 뭔가를 쉽게 찾을 수 있기를 바랍니다. 새 정규식은 다음과 같습니다. Regex : "([0-9 \\.] +) [\\ s] + ([0-9] +) [\\ s] + ([ 0-9] \\. [0-9]) [\\ s] + ([^ \\ s]. * $) "; 처음 네 열은 제대로 작동합니다. –

+0

작업에 잘못된 도구를 사용하여 포기하지 마십시오. 당신은 이미 ** 일주일 ** 이상으로 어려움을 겪고 있습니다 **. 이전 질문 중 하나에 대한 응답으로 10 분 이내에 단색 JDBC 코드로 완벽한 작업 구문 분석기 예제를 작성했습니다.이 예제에서는 파일의 열 위치에 맞게 약간 편집해야 할 수도 있습니다. 당신의 앞에있는 큰 * regex * 라벨은 무엇입니까? :) http://stackoverflow.com/questions/2360418/would-a-regex-like-this-work-for-theseline-of-text/2363260#2363260 – BalusC

답변

0

내 첫번째 생각은 공백 및 StringTokenizer를 사용하여 처음 몇 분야를 분할 한 다음 나머지 세 분야에 대한 정규 표현식을 사용하는 것이 아마도 더 쉽다는 것이다. 그렇게하면 정규 표현식을 단순화 할 수 있습니다.

+0

split()을 사용하면 훨씬 쉽습니다.'String [] parts = s.("\\ s +", 4); –

1

더 많은 문제가있을 수 있지만 첫 번째 장애물은 백 슬래시가 정규식 시스템을 만들지 않는다는 것입니다. 당신은 그들을 두 번해야합니다.

0

나는 어쩌면 당신은 정확하게 당신이 무슨 일을하는지 명확히하기 위해 좀 더 코드를 제공 할 수

(.*)\\s+(\\([0-9]{4}\\))\\s+(.*$) 

함께했다 제목과 유사에서 시작하는 부분에 대한 정규식을 마련하려고했다 정규식? 또한 this 답변에 문제가 있습니까?

0

이 정규식은 사용자가 제공 한 데이터가 제대로 작동 :

^([\d.]+)\s+(\d+)\s+([\d.]+)\s+(.+?)\s+\((\d+)\)(?:\s+\{([^{}]+))? 

을 (6 그룹 #) null가됩니다에는 자막, 마지막 그룹이없는 경우.

편집 :

import java.io.*; 
import java.util.*; 
import java.util.regex.*; 

public class Test 
{ 
    public static void main(String[] args) throws Exception 
    { 
    Pattern p = Pattern.compile(
     "^([\\d.]+)\\s+(\\d+)\\s+([\\d.]+)\\s+(.+?)\\s+\\((\\d+)\\)(?:\\s+\\{([^{}]+))?" 
    ); 
    Matcher m = p.matcher(""); 
    Scanner sc = new Scanner(new File("test.txt")); 
    while (sc.hasNextLine()) 
    { 
     String s = sc.nextLine(); 
     if (m.reset(s).find()) 
     { 
     System.out.printf("%s %8s %6s%n%s (%s) %s%n%n", 
      m.group(1), m.group(2), m.group(3), m.group(4), m.group(5), 
      m.start(6) != -1 ? m.group(6) : ""); 
     } 
    } 
    } 
} 

부분 출력 :

1000000103  50 4.5 
#1 Single (2006) THis would be a subtitle example 

2...1.2.12  8 2.7 
$1,000,000 Chance of a Lifetime (1986) 

등 ... 여기에 완벽한 예입니다.

+0

불행히도 그것은 나를 위해 작동하지 않습니다 –

+0

@angad : 그것은 나를 위해 작동합니다; 내 편집을 참조하십시오. –

+0

예. 인쇄해도 좋습니다. 하지만 여기에 문제가 나는 어쩌면 당신이 내가 변수의 각 m.group()의 가치입니다 varible에 저장하는 데 도움이 될 수있는 문제가 그때 mysql 테이블에 병 속에 삽입 나쁜 게시물 아마 내 코드가 유용 할 수 있고 그러면 내가 어디로 잘못 가고 있는지 말할 수 있습니다. –

관련 문제