简体   繁体   中英

How to ignore all char except the first and last occurence to do a substring?

I try to extract a specific content. This content is the param of findTestObject function. So I built this method :

Java Code

String testObjectExtracted = line.substring(line.indexOf("(") + 1, line.indexOf(")") + 1);
String testObjectPathExtracted = StringUtils.substringBetween(testObjectExtracted, "findTestObject(", ")");
testObjectPathExtracted = testObjectPathExtracted.substring(1, testObjectPathExtracted.length() - 1);

System.out.println(line);
System.out.println(testObjectExtracted);
System.out.println(testObjectPathExtracted);

Example OK

WebUI.click(findTestObject('Menu/span_Menu'))
findTestObject('Menu/span_Menu')
Menu/span_Menu

Example KO

WebUI.click(findTestObject('Menu/Test/link (AA)'))
findTestObject('Menu/Test/link (AA)
Menu/Test/link (A
// Expected result : Menu/Test/link (AA)

However as you can see on above examples, I'm facing an problem if there is ( or ) in the path because my substring is based on ( and ) .

Do you have any solution to solve it please ? Thank you.

Solution is to use lastIndexOf() method.

String testObjectExtracted = line.substring(line.indexOf("(") + 1, line.lastIndexOf(")"));
String testObjectPathExtracted = testObjectExtracted.substring(testObjectExtracted.indexOf("(") + 1, testObjectExtracted.lastIndexOf(")"));
testObjectPathExtracted = testObjectPathExtracted.substring(1, testObjectPathExtracted.length() - 1);

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