Mojtaba Yeganeh
Mojtaba Yeganeh

Reputation: 2922

Request a Regular Expression

Here is my text as Entry :

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

I need to get [LoadImage:'*'] start and end position(s) as an array in java

Upvotes: 2

Views: 96

Answers (4)

Harpreet Singh
Harpreet Singh

Reputation: 2671

/* 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));
        }
    }
}

output

'image1.jpg'

'image2.jpg'

Upvotes: 1

Zarathustra
Zarathustra

Reputation: 2953

Your regex: .*\[(.*)\] in group 1 is what you are looking for. Take a look here: http://fiddle.re/x9egb

Upvotes: 0

nervosol
nervosol

Reputation: 1291

Nishant already gave you answer, but if you afraid of []inside apostrophe use:

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

Upvotes: 0

Braj
Braj

Reputation: 46861

Is this you are looking for? If yes then use grouping feature of regex that is grouped by using parenthesis () and get it using Matcher#group() method.

Sample code:

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());
    }
}

output:

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

Upvotes: 1

Related Questions