请求正则表达式

时间:2014-06-22 07:01:32

标签: java regex

这是我的文字作为条目:

This is An Image File [LoadImage:'image1.jpg']
this is Another Image [LoadImage:'image2.jpg']

我需要将[LoadImage:'*']开始和结束位置作为java中的数组

4 个答案:

答案 0 :(得分:1)

这是你要找的吗?如果是,则使用正则表达式的分组功能,该功能使用括号()进行分组,并使用Matcher#group()方法获取。

示例代码:

String[] array = new String[] { "This is An Image File [LoadImage:'image1.jpg']",
        "this is Another Image [LoadImage:'image2.jpg']" };

Pattern p = Pattern.compile("(\\[LoadImage:.*?\\])");
for (String s : array) {
    Matcher m = p.matcher(s);
    if (m.find()) {
        System.out.println(s + " : found:" + m.group(1) + " : start:" + m.start()
                + " : end:" + m.end());
    }
}

输出:

This is An Image File [LoadImage:'image1.jpg'] : found:[LoadImage:'image1.jpg'] : start:22 : end:46
this is Another Image [LoadImage:'image2.jpg'] : found:[LoadImage:'image2.jpg'] : start:22 : end:46

答案 1 :(得分:1)

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "This is An Image File [LoadImage:'image1.jpg'] this is Another Image [LoadImage:'image2.jpg']";

        Pattern p = Pattern.compile("\\[LoadImage:(.*?)\\]");
        Matcher m = p.matcher(s);

        while(m.find()) {
            System.out.println(m.group(1));
        }
    }
}

<强>输出

&#39; image1.jpg&#39;

&#39; image2.jpg&#39;

答案 2 :(得分:0)

Nishant已经给你回答,但如果你害怕[]撇号内使用:

int[] arr = new int[]{str.indexOf('['), str.lastIndexOf(']')}

答案 3 :(得分:0)

您的正则表达式:第1组中的.*\[(.*)\]是您正在寻找的。看看这里:http://fiddle.re/x9egb