Dupinder Singh
Dupinder Singh

Reputation: 7759

Regex to find text between string pattren

String: [img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]

Result I Want: [img border=0]images/bbcode/sets/misc/bullet_go.png[/img] without /scm/ text.

Issue: Text scm is not static, could be any other text in data.

What I want: Have a look to this string
[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]
Regex which can fetch a text between ] and images/bbcode/ so the regex will detect the \scm\ text and then can remove this \scm\ from String data and end result will look like [img border=0]images/bbcode/sets/misc/bullet_go.png[/img]

PS: I am implementing this logic in Java.

Upvotes: 1

Views: 102

Answers (4)

Dupinder Singh
Dupinder Singh

Reputation: 7759

I found one more way to solve this same problem

String pattereString = "].*/images";

        String maineString = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
        maineString = maineString.replaceAll(pattereString, "images");
        System.out.println(maineString);

Output:

[img border=0]images/bbcode/sets/misc/bullet_go.png[/img]

Upvotes: 0

CoderX
CoderX

Reputation: 302

I have captured text between '] and /images..' and replace this text with "". Check the following demo:

String s = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
s = s.replaceAll("(?<=])/[^/]+/","");
System.out.println(s);

Upvotes: 1

Majid Roustaei
Majid Roustaei

Reputation: 1754

you can reach the goal without using regex, too.

since you said that the other parts are static, try this:

String myStr = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
myStr = "[img border=0]" + myStr.substring(myStr.indexOf("images"));
System.out.println(myStr);

and the output will be:

[img border=0]images/bbcode/sets/misc/bullet_go.png[/img]

Upvotes: 2

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

if [img border=0] dynamic, you can take all except /scm/

some demo

   String input = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";

    Pattern p = Pattern.compile("(^.*\\])\\/.*?\\/(.*$)");

    Matcher m = p.matcher(input);
    if (m.find()) {
        String output = m.replaceFirst("$1$2"); 
        System.out.println(output);
    }



 // -> [img border=0]images/bbcode/sets/misc/bullet_go.png[/img]

Upvotes: 1

Related Questions