简体   繁体   English

如何忽略除第一次和最后一次出现之外的所有字符来执行子字符串?

[英]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.该内容是findTestObject函数的参数。 So I built this method :所以我建立了这个方法:

Java Code Java代码

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示例 OK

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

Example KO示例 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.解决方案是使用lastIndexOf()方法。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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