从字符串中获取标记之间的字符串

时间:2014-04-16 16:18:05

标签: java android regex string vcard

我对Regex不太熟悉,所以我在这里问。

我有这样的字符串:

BEGIN:VCARD
VERSION:3.0
FN:A Sirius Swimwear Collection
N:Collection;A;Sirius Swimwear;;
TEL;TYPE=HOME:22448
TEL;TYPE=CELL:52316
ADR:;Taylors Road;;;;;
ORG:Norfolk Phone Book
END:VCARD
BEGIN:VCARD
VERSION:3.0
FN:A Walk in the Wild
N:Wild;A;Walk in the;;
TEL;TYPE=HOME:22502
item1.TEL:23205
item1.X-ABLabel:Facsimile
ADR:;Grassy Road;;;;;
ORG:Norfolk Phone Book
END:VCARD
BEGIN:VCARD
VERSION:3.0
FN:AATA Orn Tours
N:Tours;AATA;Orn;;
TEL;TYPE=HOME:23611
TEL;TYPE=CELL:50755
ADR:;Bookings;;;;;
ORG:Norfolk Phone Book
END:VCARD
BEGIN:VCARD
VERSION:3.0
FN:Aatuti Art
N:Art;Aatuti;;;
TEL;TYPE=HOME:23669
ADR:;The Village;;;;;
ORG:Norfolk Phone Book
END:VCARD
BEGIN:VCARD
VERSION:3.0
FN:ABC Hobby Centre
N:Centre;ABC;Hobby;;
TEL;TYPE=HOME:22139
ADR:;Taylors Road;;;;;
ORG:Norfolk Phone Book
END:VCARD
(...)

对于那些熟悉的人来说,它是一堆VCards,我想从String中逐个获得一个VCard。所以,我想把它分成多个字符串。我想要使​​用BEGIN:VCARDEND:VCARD代码进行拆分

最终:

vcard1 = "BEGIN:VCARD
    VERSION:3.0
    FN:A Sirius Swimwear Collection
    N:Collection;A;Sirius Swimwear;;
    TEL;TYPE=HOME:22448
    TEL;TYPE=CELL:52316
    ADR:;Taylors Road;;;;;
    ORG:Norfolk Phone Book
    END:VCARD";

vcard2 = "BEGIN:VCARD
    VERSION:3.0
    FN:A Walk in the Wild
    N:Wild;A;Walk in the;;
    TEL;TYPE=HOME:22502
    item1.TEL:23205
    item1.X-ABLabel:Facsimile
    ADR:;Grassy Road;;;;;
    ORG:Norfolk Phone Book
    END:VCARD";

vcard3 = "BEGIN:VCARD
    VERSION:3.0
    FN:AATA Orn Tours
    N:Tours;AATA;Orn;;
    TEL;TYPE=HOME:23611
    TEL;TYPE=CELL:50755
    ADR:;Bookings;;;;;
    ORG:Norfolk Phone Book
    END:VCARD";

老实说,我只需要正确的正则表达式模式作为我能够做到的循环。 这是在JAVA(适用于Android)。

修改

这是我迄今为止尝试过的,但没有成功:

if(vcard.contains("VERSION:"))
        {
            Log.d(TAG, "Creating the patterns");
            Pattern p = Pattern.compile("BEGIN:VCARD(.*)END:VCARD");

            Matcher m = p.matcher(vcard);

            if (m.find()) 
            {

                Log.d(TAG, "Find: " + m.group(1));

            }
            Log.d(TAG, "Not found anything");

2 个答案:

答案 0 :(得分:4)

您可以在正则表达式中使用Pattern.DOTALL。它意味着In dotall mode, the expression dot(.) matches any character, including a line terminator,它将帮助您匹配多行模式。

String input = "__YOUR__VCARDS__";
Pattern pattern = Pattern.compile("(BEGIN:VCARD.*?END:VCARD)", Pattern.DOTALL);
Matcher m = pattern.matcher(input);
while (m.find()) {
    System.out.println(m.group(1));
}

答案 1 :(得分:0)

您应该尝试ez-vcard。它是一个适用于Android的Java vCard库。

免责声明:我是作者;)