英文:
How to split this Xpath?
问题
givenString = "/DATA[1]/ASSET[1]/DET[5]/INT[1]/VAL[1]/text()[1]"
findString = "DET"
我期望的输出是:"/DATA[1]/ASSET[1]/DET[5]/"
我需要找到字符串"DET",以及直到第一个"/"之前的其他字符。
英文:
givenString = "/DATA[1]/ASSET[1]/DET[5]/INT[1]/VAL[1]/text()[1]"
findString = "DET"
Output I am expecting is "/DATA[1]/ASSET[1]/DET[5]/"
I have to find the String "DET" and other characters until I reach first "/"
答案1
得分: 2
假设DET
只会出现一次,你可以在这里使用正则表达式替换:
String givenString = "/DATA[1]/ASSET[1]/DET[5]/INT[1]/VAL[1]/text()[1]";
String findString = "DET";
String output = givenString.replaceAll("(.*/" + findString + "[^/]*/).*", "$1");
System.out.println(output);
这会打印出:
/DATA[1]/ASSET[1]/DET[5]/
这里的想法是在以下正则表达式模式上匹配整个字符串:
^(.*/DET[^/]*/).*$
然后,我们用仅第一个捕获组$1
进行替换,该捕获组应该包含你想要的路径。
英文:
Assuming that DET
would only appear once, you could use a regex replacement here:
<!-- language: java -->
String givenString = "/DATA[1]/ASSET[1]/DET[5]/INT[1]/VAL[1]/text()[1]";
String findString = "DET";
String output = givenString.replaceAll("(.*/" + findString + "[^/]*/).*", "$1");
System.out.println(output);
This prints:
/DATA[1]/ASSET[1]/DET[5]/
The idea here is to match the entire string on the following regex pattern:
<!-- language: regex -->
^(.*/DET[^/]*/).*$
Then, we replace with just the first capture group $1
, which should contain the path you want.
答案2
得分: 0
另一种不使用正则表达式的方法如下:
public static void main(String[] args) {
String givenString = "/DATA[1]/ASSET[1]/DET[5]/INT[1]/VAL[1]/text()[1]";
String findString = "DET";
List<String> stringList = Arrays.asList(givenString.split("/"));
StringBuilder expectedOutput = new StringBuilder();
Iterator itr = stringList.iterator();
while (itr.hasNext()) {
String temp = (String) itr.next();
expectedOutput.append(temp + "/");
if (temp.startsWith("DET"))
break;
}
System.out.println(expectedOutput.toString());
}
//Output
/DATA[1]/ASSET[1]/DET[5]/
英文:
An alternate approach without using regex would be this :
public static void main(String[] args) {
String givenString = "/DATA[1]/ASSET[1]/DET[5]/INT[1]/VAL[1]/text()[1]" ;
String findString = "DET";
List<String> stringList = Arrays.asList(givenString.split("/"));
StringBuilder expectedOutput = new StringBuilder();
Iterator itr = stringList.iterator();
while (itr.hasNext()){
String temp = (String) itr.next();
expectedOutput.append(temp+"/");
if(temp.startsWith("DET"))
break;
}
System.out.println(expectedOutput.toString());
}
//Output
/DATA[1]/ASSET[1]/DET[5]/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论