Torbir
Torbir

Reputation: 67

Java regular expressions: ignore all characters until certain character. regex

I am writing a java program to download PDFs automatically from a website. My program reads through an excel file, and downloads the PDF for every account number in the excel file. In the browser, the account is selected from a menu, however, the menu has the format of # storenumber - accountnumber (ex. # 1234 - 987654321). I do not have access to the store numbers. A simple solution would be just to ignore the first x characters, but some of the store numbers are different length so this does not work.

Is it possible for java to disregard all the characters before the - , and if it is could you write out this expression.

I am using it with selenium and firefox webdriver, making it harder to simply seperate and save the string. Meaning I do NOT have the string in memory, it is coming from the browser.

This is what my code would look like IF i had the store numbers (but i dont).

new Select(driver.findElement(By.id("ctl00_main_ddlAssocAccountNumbers"))).selectByVisibleText(storeNum + " - " + accountNum);

Any other solutions or suggestions are appreciated.

Thanks, Torbir

Upvotes: 1

Views: 879

Answers (1)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

If the format # storenumber - accountnumber is fixed better use a split()

accountNum = accountNum.split(" - ")[1];

EDIT :
As per your updated post and comments, I think you're looking to make a partial match on just the user account number while using Selenium's selectByVisibleText() method which does not accept any wildcards or regular expressions.

But here's how you can achieve this behaviour by doing a sub-string match using contains():

Select select = new Select(driver.findElement(
                    By.id("ctl00_main_ddlAssocAccountNumbers")));
List<WebElement> listOfOptions = select.getOptions();
for (WebElement option : listOfOptions) {
    String storeAndAcctNum = option.getText();
    if (storeAndAcctNum.contains(accountNum)) { // if sub-string matches
        select.selectByVisibleText(storeAndAcctNum); // fire select as usual
        break; // out of the loop
    }
}

Upvotes: 4

Related Questions