ITI0011:praktikum 16 G12

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><title>blah</title>" + "<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) { int titleStart = xml.indexOf("<book>", pos); if (titleStart == -1) break; // no more book tags titleStart = xml.indexOf("<title>", titleStart); if (titleStart == -1) break; // no more titles int titleEnd = xml.indexOf("</title>", titleStart); String title = xml.substring(titleStart + "<title>".length(), titleEnd); System.out.println(title); pos = titleEnd; }

// regex /* * sümbol - tähendab sama sümbolit * x? - kas on või ei ole "x", 0 või 1 korda "x" * x* - 0.. korda * x+ - 1.. korda * x{3} - täpselt kolm korda * x{3,5} - kolm kuni viis korda * * . - suvaline sümbol * [abc] - kas "a" või "b" või "c" * [a-z] - kõik tähed 'a'...'z' * [a-zA-Z] - * [0-9] - kõik numbrid * * [^abc] - mitte "a" ega "b" ega "c", kõik ülejäänud sobivad * * [a-z]? - kas on väike täht või ei ole (0..1 korda väiketähte) * */ match("this is colorrr", "colou?r"); match("this is colour", "colou?r"); match("this is colouuuu", "colou*r?"); match("this is colouuuu", "colou+r?");

match("this is greey", "gr.y"); match("this is gray", "gr[ae]y");

match("this is graey", "gr[ae]*y"); match("123456789", "[0-9]{1,8}");

match("this is colorrr", "[^ ]is"); match("binary number 00101010100010", "(01)+");

match("my number is +37212345678", "([0-9]{3})([0-9]*)");

match("this is colorrr", "(i(s))"); match("<title>Kevade</title>", "<title>(.*)</title>"); match(xml, "<title>(.*)</title>"); // lazy // match("AtereB AtulemastB", "A([^B]*)B"); }

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>