Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 342
  • Last Modified:

java pattern matcher find string before the matching

I have a string like this:
/temp/2345183/one:page/jiie200u3uuc

I need to take everything before /one:page (the number of fields might vary before /this:page).  What's the best way to do this?

In this example, I need find the "/temp/2345183" string.

Thanks!
0
mybluegrass
Asked:
mybluegrass
2 Solutions
 
käµfm³d 👽Commented:
The following pattern should suffice. You text will be in group 1.
(?s)^(.*?)/one:page

Open in new window

0
 
mybluegrassAuthor Commented:
I tried this but it kept complaining no match found:

path = /temporary/cm/94d0bfb0_5ead_49c0/one:page/3bbfa669_c201_4b8

Pattern p = Pattern.compile("(?s)^(.*?)/one:page.*");
        Matcher m = p.matcher(path);
        docPath = m.group(1);
0
 
käµfm³d 👽Commented:
Not sure why that's not working. Let's try a different route. I tested this in NetBeans and it worked as intended:
String path = "/temporary/cm/94d0bfb0_5ead_49c0/one:page/3bbfa669_c201_4b8";
Pattern p = Pattern.compile("/one:page.*");
Matcher m = p.matcher(path);
String docPath = m.replaceAll("");
System.out.println(docPath);

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
käµfm³d 👽Commented:
The previous one didn't work because you have to call find() prior to accessing the group:
String path = "/temporary/cm/94d0bfb0_5ead_49c0/one:page/3bbfa669_c201_4b8";
Pattern p = Pattern.compile("(?s)^(.*?)/one:page");
Matcher m = p.matcher(path);
m.find();
String docPath = m.group(1);
System.out.println(docPath);

Open in new window

0
 
Justin MathewsCommented:
Try this:


  String sourcestring = "/temp/2345183/one:page/jiie200u3uuc";

  Pattern re = Pattern.compile("(.+)\\/one:page");

  Matcher m = re.matcher(sourcestring);
  int mIdx = 0;
    if (m.find())
        System.out.println( m.group(1));
    }

Open in new window

0
 
CEHJCommented:
You could simplify that to
s = s.replaceAll("(.*?)/one:page.*", "$1");

Open in new window

0
 
objectsCommented:
try this:

String fields = s.replaceAll("/one:page.*", "");
0
 
CEHJCommented:
Or
String fields = s.substring(0, s.indexOf("/one:page"));
0
 
CEHJCommented:
:)
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now