0

I have to implement almost similar system to Spring PathVariable. I know how to parse my own url definition:

Definition :

blog-{String}-{Integer}

Code :

Pattern p = Pattern.compile("\\{.+?\\}");
Matcher m = p.matcher(pathFormat);
while(m.find())
{
    String group = m.group();
    // ...
}

But how can I parse real urls with my format? If real url was like

blog-my-first-blogging-10001

Real url doesn't have brackets, so how can I use regex to match my groups. Type of group is known, but how to match without brackets ?

2 Answers 2

1

Maybe a bit silly, but why not try:

 String restOfPath = pathFormat.substring(5); //eliminate 'blog-' prefix
 int lastDash = restOfPath.lastIndexOf('-'); //find the last '-'
 String title = restOfPath.substring(0, lastDash);  // take what's before '-'
 String id = restOfPath.substring(lastDash + 1); // take the rest.

??

Unless your paths can get more complicated than blog-{String}-{Integer} there's no need for regex here.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanx for input, but I need generic solution that can match almost any possible url, just like Spring PathVariable ...
@newbie the problem you have is that the string you're capturing can contain the path separator. AFAIK spring and probably all implementations of URI templates will bork if you try to match word/a/lot/of/words/anotherword against word/{something}/anotherword (ie it won't match). That's your case, only with dashes instead of slashes.
Oops, that's right, url template must have separator to work, I missed that.
1

It is not clear (to me at least) what you are trying to do, here is how I use spring path variables :

@RequestMapping(value = "/{MyBlog}/{myVar}", method = RequestMethod.GET)
public ModelAndView getBlog(@PathVariable final String MyBlog, @PathVariable final Integer myVar)    {
  final ModelAndView mav  =  new ModelAndView(MyBlog);
  mav.addObject("myVar", myVar);
  // in actuality do lots of other thigns 
  return mav;
}

And it would accessed using the url http://myApp.com/AnyBlogName/21 where 21 can be any number, and AnyblogName can be string you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.