简体   繁体   中英

Extract text between URL with Java

I want to extract from this URL: "https://www.newhomesource.com/community/az/cave-creek/galloway-ridge-by-k-hovnanian-homes/148397" the text "k-hovnanian-homes"

The thing is that I manage to obtain this String: "k-hovnanian-homes/148397" but I can't remove the /148397. Is there a way I can remove it?

Here is what I have

 import org.openqa.selenium.By;
 import org.openqa.selenium.WebDriver;
 import org.testng.annotations.BeforeTest;
 import org.testng.annotations.Test;

 public void VerifyURL(){
    String URL= "https://www.newhomesource.com/community/az/cave-creek/galloway-ridge-by-k- 
    hovnanian-homes/148397";
   
    String Final = URL.substring(URL.indexOf("by-") + 3);
    System.out.println(Final);

 }

Also the numbers after the "/" can change so take that in count

I'm Selenium WebDriver and TestNG so that's why the imports :)

Update: Another URL example could be: https://www.newhomesource.com/community/tn/lebanon/hampton-chase-legacy-collection-by-beazer-homes/152012

Simply use lastIndexOf

 String URL= "https://www.newhomesource.com/community/az/cave-creek/galloway-ridge-by-k-hovnanian-homes/148397";

 String Final = URL.substring(URL.indexOf("by-") + 3,URL.lastIndexOf("/"));
 System.out.println(Final);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM