java - java 和 android 之间 java.util.regex.Matcher 中 usePattern() 的不同使得这个任务变得困难

标签 java android regex

有一长串结构为<A>N</C></B> <B >E</B> <B >N</B>并重复多次。 (A,B,C,E,N各代表不同的字符串)
例如:
<target="FmRight">200910102</A></TD> <TD Nowrap >alvin</TD> <TD Nowrap >93</TD> <target="FmRight">200910103</A></TD> <TD Nowrap >Tom</TD> <TD Nowrap >85</TD>

我想检索标签之间的字符串,所以我写了两个正则表达式

"target=\"FmRight\">\\d+"

"<TD Nowrap >[^<]*</TD>"

这是测试代码

    Pattern p1 = Pattern.compile("target=\"FmRight\">\\d+");
    Pattern p2 = Pattern.compile("<TD Nowrap >[^<]*</TD>");
    Matcher m = p1.matcher(text);
    int count = 0;
    for (int i = 0; i < 3; i++) {
        if(m.find())
            System.out.println(m.group().split(">")[1]);
        m.usePattern(p2);
        count=0;
        for(int j=0;j<2;j++){
            if(m.find())
                System.out.println(m.group().split(">")[1].split("<")[0]);
        }
        m.usePattern(p1);
        count=1;
    }

在jre中可以正常运行,在android中就不行了。
因为在java中usePattern()

This method causes this matcher to lose information about the groups of the last match that occurred. The matcher's position in the input is maintained and its last append position is unaffected.

在安卓中 usePattern()

Sets a new pattern for the Matcher. Results of a previous find get lost. The next attempt >to find an occurrence of the Pattern in the string will start at the beginning of the >input.

那么,如何在 android 中更改 Pattern 时保持输入位置?

最佳答案

您可以使用 region() 方法强制匹配器从上次 find() 结束的位置开始查找。

Pattern p1 = Pattern.compile("target=\"FmRight\">\\d+");
Pattern p2 = Pattern.compile("<TD Nowrap >[^<]*</TD>");
Matcher m = p1.matcher(text);
int count = 0;
int regionStart= 0;                          // <-----
for (int i = 0; i < 3; i++) {
    if(m.find()) {
        regionStart = m.end();               // <-----
        System.out.println(m.group().split(">")[1]);
    }
    m.usePattern(p2);
    m.region(regionStart, m.regionEnd());    // <-----
    count=0;
    for(int j=0;j<2;j++){
        if(m.find()) {
            regionStart = m.end();           // <-----
            System.out.println(m.group().split(">")[1].split("<")[0]);
        }
    }
    m.usePattern(p1);
    m.region(regionStart, m.regionEnd());    // <-----
    count=1;
}

编辑:更正:您应该能够做到这一点。我不会说 Android,所以我不知道他们是否也搞砸了。 :-/

关于java - java 和 android 之间 java.util.regex.Matcher 中 usePattern() 的不同使得这个任务变得困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9544953/

相关文章:

java - 如何在 FlowLayout 或 GridLayout 中手动放置组件?

android - Google Play Developer Console 为我提供了两个不同轨道的相同选择加入网址

Python正则表达式替换数字-1

java - 触摸事件行为异常

Java - 限制可以调用的方法

android - 文件下载完成后如何自动安装APK(私有(private)托管)

java - 在java中使用正则表达式,解析文本的各个部分

PHP PCRE(正则表达式)不支持 UTF-8?

java: datainputstream: 读取调用在等待数据时占用处理器时间吗?

android - 在启用混淆器的情况下以 Release模式编译 Android 应用程序时出现问题