Erinevus lehekülje "ITI0011:praktikum 16" redaktsioonide vahel

Allikas: Kursused
Mine navigeerimisribale Mine otsikasti
(Uus lehekülg: '<source lang="java" import java.util.regex.Matcher; import java.util.regex.Pattern; public class XmlParsingExample { public static void main(String[] args) throws BookShopAp...')
 
 
1. rida: 1. rida:
<source lang="java"
+
<source lang="java">
  
 
import java.util.regex.Matcher;
 
import java.util.regex.Matcher;

Viimane redaktsioon: 26. märts 2015, kell 08:51

<source lang="java">

import java.util.regex.Matcher; import java.util.regex.Pattern;


public class XmlParsingExample {

public static void main(String[] args) throws BookShopApiException { String xml = "<root><books>" + "<book><title>Kevade</title><author>Luts</author></book>" + "<book><title>Sügis</title><author>Luts</author></book>" + "</books></root>"; System.out.println(xml);

// 1) manual, String meetodid int pos = 0; while (true) { // otsin järgneva "<book>" int bookPos = xml.indexOf("<book>", pos); if (bookPos == -1) { break; } // otsin järgneva "<title>" int titleStart = xml.indexOf("<title>", bookPos); // otsin järgneva "</title>" int titleEnd = xml.indexOf("</title>", titleStart); // nende vahel on title String title = xml.substring(titleStart + "<title>".length(), titleEnd); System.out.println(title); // nihutame järjehoidjat pos = bookPos + 1; } // 2) regexp String s = "gray"; /* * x? - "x" 0 või 1 kord * x* - "x" 0 ... korda * x+ - "x" 1... korda * x{3} - 3 korda * x{3,5} - 3 kuni 5 korda * * [ae] - "a" või "e" * [a-zA-Z] - "a", "b", ... "z" * [0-9] kõik numbrid * . - suvaline sümbol * * [^a] - ^ otsi kõike, mis ei ole [] vahel * [^a-z] - ükskõik mis sümbol, mis pole a-z * * a? * (at)? * * [ae]? * * [ae]+ */ Pattern p = Pattern.compile("gr.y"); Matcher m = p.matcher(s); if (m.find()) { System.out.println("found at:" + m.start() + " ends at:" + m.end()); } System.out.println("---"); // 1) lazy match p = Pattern.compile("<title>([^<]*)(</title>)"); m = p.matcher(xml); while (m.find()) { System.out.println("found at:" + m.start() + " ends at:" + m.end()); System.out.println(m.group(0)); System.out.println(m.group(1)); System.out.println(m.group(2)); }

}

} </source>