1

I have the following urls

/es-es/Replica-2300/saliffanag/winsrow
/es-de/Bat-00/saliffanag/winsrow
/es-it/Re-2300/saliffanag/winsrow
/es-../
etc..

And I need a pattern that captures only /es-es/ or /es-de/ or /es-it/ (the first /...-.../) in Java.

I've tried with this

"[^/]*/([^/]*)/"

But is not working

How can I achieve this?

Nexussim Lements
  • 685
  • 1
  • 10
  • 29
  • How do you apply that regex? Are you sure the paths always start with a slash? Also please define "it is not working" - do you get too many or too few matches? The regex in general should be ok, you just might need to add `.*` at the end to make it consume the entire input (otherwise you might get multiple matches per path, depending on how you apply it). – Thomas Apr 18 '19 at 11:37
  • as an advice in regex start using regex engine before put it into action – zerocool Apr 18 '19 at 11:38
  • Possible duplicate of [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – Starmixcraft Apr 18 '19 at 11:43

3 Answers3

3

Just use a split:

"/es-es/Replica-2300/saliffanag/winsrow".split("/", 3)[1] 

returns "es-es" after that just add the / back on

For variable URLs:

String[] split = "padding/test/for/loop/es-es/Replica-2300/saliffanag/winsrow".split("/");
String result = "";  

for(String s : split){
  if(s.length() != 5){ continue;} 
  if(s.charAt(2) == '-'){
    result = s; //if you need the '/' just use result = "/" + s "/";
    break;
  }
}
Starmixcraft
  • 389
  • 1
  • 14
1

Here you go:

\/(es-[a-z]+)\/

Try the expression out at Regex101.

  • \/ matches the / literally - must be escaped
  • () is the capturing group
  • es- matches self literally
  • [a-z]+ matches one or more letters together

If the input might be ex. it-it, you want to use \/(\[a-z\]+-\[a-z\]+)\/.

On the other hand, if you have a defined list of the possible suffixes, use \/(es-(?:es|de|it))\/ where (?:) is a non-capturing group.

Nikolas Charalambidis
  • 35,162
  • 12
  • 84
  • 155
0
\/([a-z]{2}-[a-z]{2})\/

See here: https://regexr.com/4chaj

Regexr will explain in detail how this particular regex is working. Just click on 'Explain'

Damien O'Reilly
  • 882
  • 5
  • 12