Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在android中使用replaceAll和regex提取字符串中的数字_Android_Regex_Extract_Replaceall - Fatal编程技术网

在android中使用replaceAll和regex提取字符串中的数字

在android中使用replaceAll和regex提取字符串中的数字,android,regex,extract,replaceall,Android,Regex,Extract,Replaceall,我想从一个长字符串中提取一个数字 我的代码是: private String[] icons; private String[] pages; icons=geticons.split(";"); pages=article.split(";"); int i=0; for (String page:pages) { pages[

我想从一个长字符串中提取一个数字 我的代码是:

      private String[] icons;
  private String[] pages;
            icons=geticons.split(";");
            pages=article.split(";");
            int i=0;
            for (String page:pages)
            {
                pages[i].replaceAll("(image)([0-9])", icons[$2]);
                i++;
       }
但是图标[$2]错误。 如何解决它

例如: 图标元素:

{"yahoo.com/logo.jpg" , "yahoo.com/logo3.jpg", "yahoo.com/logo8.jpg"}
页面元素:

"hello how image0 ar you? where image3 are you? image8"
输出:

"hello how yahoo.com/logo.jpg  ar you? where yahoo.com/logo3.jpg are you? yahoo.com/logo8.jpg"

首先,您的for循环毫无意义。要么使用i,要么完全忽略它:

 for (String page:pages) {
      page.replaceAll("(image)([0-9])", icons[2]);
  }
其次,java数组中的元素通过索引直接访问:

arr[index]
在您的情况下,这将是图标[2]

最后,正则表达式将只考虑图像名称中的一个数字。因此,如果您有图像10,例如,它将无法正确识别。我将使用:

"(image)([0-9]+)"
因为+量词表示“一次或多次”。另外,您还可以用表示数字的
\\d
替换
[0-9]

尝试以下方法:

Pattern pattern = Pattern.compile("(image)([0-9]+)");

for(int i = 0; i < pages.length; i++) {

    Matcher matcher = pattern.matcher(pages[i]);
    while(matcher.find()) {

        String imageNumber = matcher.group(2); // I guess this is what you wanted to get with '$2'
        int n = Integer.parseInt(imageNumber);
        pages[i] = pages[i].replace(matcher.group(0), icons[n]);
    }
}
Pattern=Pattern.compile(([0-9]+)”);
对于(int i=0;i
为什么要使用“$”符号?在java中,您可以访问如下数组元素:
图标[2]
。或者我遗漏了什么?我想访问([0-9]),并将其用作数组的访问元素?为什么不使用
i
作为索引?我有一个字符串,例如“你好,你的图像如何0你的图像在哪里2”我想用图像+nmber替换图像的url和编号,所以我想了解它你应该在你的问题中添加一两个示例,与您的输入和预期的输出