ITI0011:praktikum 16 G5

Allikas: Kursused
Mine navigeerimisribale Mine otsikasti

<source lang="java">

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

public class XmlPArsingExample {

public static void main(String[] args) { 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 int pos = 0; while (true) { // otsi "<title>" int titleStartPos = xml.indexOf("<title>", pos); if (titleStartPos == -1) break; // ei leitud enam // otsi "</title>" int titleEndPos = xml.indexOf("</title>", pos); // nende vahel on title String title = xml.substring(titleStartPos + "<title>".length(), titleEndPos); System.out.println(title); pos = titleEndPos + 1; }

// regex /* * x? - kas x on või ei ole. x 0 või 1 korda * x+ - kas 1 või rohkem korda * x* - kas 0 või rohkem korda * x{3} - täpselt 3 korda * x{3,5} - 3-5 korda * * . - suvaline sümbol * [abc] - kas "a" või "b" või "c" * [a-zA-Z] - vahemikuga * [0-9] - üks number * [^abs] - kõik sümbolid, mis ei ole a, b, s * * [a-z]+ - abc * * \( - otsib "(" * () - grupeerimine * */ match("this is grey colouuuur ", "[a-z]{3}"); match("01001010101000", "(01)+"); match(xml, "(<t(it)le>)(.*)"); match(xml, "<title>(.*)</title>"); match("AtereB Atere2B AtereB", "A([^B]*)B"); /* String s = "this is grey colouuuur "; Pattern p = Pattern.compile("[a-z]{2,4}"); Matcher m = p.matcher(s); while (m.find()) { System.out.println("found at: " + m.start() + " ends at:" + m.end()); System.out.println(m.group(0)); } */ }

public static void match(String s, String pattern) { System.out.println("----"); System.out.println("s:" + s); System.out.println("pattern:" + pattern); Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(s); while (m.find()) { System.out.println("found at: " + m.start() + " ends at:" + m.end()); System.out.println(m.group(0)); for (int i = 1; i <= m.groupCount(); i++) { System.out.println("group " + i + ": " + m.group(i)); } }

}

}

</source>