Reputation: 787
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?
Upvotes: 1
Views: 285
Reputation: 397
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;
}
}
Upvotes: 3
Reputation: 992
\/([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'
Upvotes: 0
Reputation: 44388
Here you go:
\/(es-[a-z]+)\/
Try the expression out at Regex101.
\/
matches the /
literally - must be escaped()
is the capturing groupes-
matches self literally[a-z]+
matches one or more letters togetherIf 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.
Upvotes: 1