Monday 23 September 2013

Truncate special characters using Java Patterns | Selenium

Truncating string that holds special characters, !@#$%^&*(){}[]? made easy using Java patterns on Selenium.
For Example, take a string (4000).  Here,
Actual Result: string (4000) | Expected Result: integer 4000

1| remove parentheses
2| convert string to integer

List<WebElement> count = driver.findElement(By.cssSelector("Value")).findElements(By.tagName("li"));
//getting iTable count    
String a = count.get(0).findElement(By.cssSelector("Value")).getText();

Pattern pt = Pattern.compile("[()]"); \\ special characters can be of anything  !@#$%^&*(){}[]?
Matcher match= pt.matcher(a);
while(match.find())
{
    String s= match.group();
    a=a.replaceAll("\\"+s, ""); \\ remove parentheses
}

System.out.println("Total count in string: " + a);

int value = Integer.parseInt(a); \\ convert string to integer


Example |2|

WebElement element = driver.findElement(By.xpath("Value"));    
String truncelem = element.getText();
String result = truncelem.replaceAll("[()]","");

No comments:

Post a Comment