• # Les regexp ramollissent le cerveau

    Posté par (site web personnel) . En réponse au journal Créer un livre dont vous êtes le héros avec des outils libres + question sur les regex. Évalué à 2.

    Pourquoi utiliser des regexp alors qu'un simple parser suffit (oui je sais faire ça en java c'est utiliser une bombe atomique pour tuer une mouche :-)
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    public class Digraph
    {
     public static void main(String[] args)
     {
    	if (args.length != 1) {
    	 System.out.println("usage: java Diagraph <graph_file>");
    	 System.exit(-1);
    	}
    	File f = new File(args[0]);
    	try {
    	 Digraph graph = new Digraph(f);
    	} catch (IOException e) {
    	 e.printStackTrace();
    	 System.exit(-2);
    	}
     }
     Digraph(File f) throws IOException
     {
    	FileReader reader = new FileReader(f);
    	int key = 0;
    	int cur = 0;
    	for (;;) {
    	 int c = reader.read();
    	 if (c == -1)
    		break;
    	 if (Character.isWhitespace((char)c))
    		continue;
    	 switch (c) {
    	 case '1':
    	 case '2':
    	 case '3':
    	 case '4':
    	 case '5':
    	 case '6':
    	 case '7':
    	 case '8':
    	 case '9':
    	 case '0':
    		cur = 10 * cur + (c - '0');
    		break;
    	 case '-':
    		break;
    	 case '>':
    		key = cur;
    		cur = 0;
    		break;
    	 case ';':
    		System.out.printf("%d->%d\n", key, cur);
    		cur = 0;
    		break;
    	 default:
    		throw new IOException(String.format("Unexpected char: %c", c));
    	 }
    	}
     }
    }