[英]use regex in String.Split() for extract text between { and } in java
我有一個像這樣的字符串:
String str = ${farsiName} - {symbolName}
我想使用split方法從帶有正則表達式的字符串中查找和提取farsiName和symbolName 。 我發現此解決方案https://stackoverflow.com/a/4006273/2670847可以執行以下操作:
String in = "Item(s): [item1.test],[item2.qa],[item3.production]";
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(in);
while(m.find()) {
System.out.println(m.group(1));
}
但是我想知道,我可以在String類中使用類似的正則表達式作為split方法嗎?
您步入正軌。 只需更換括號和字符串。
String n ="${farsiName} - {symbolName}";
Pattern p = Pattern.compile("\\{(.*?)\\}");
Matcher m = p.matcher(n);
while(m.find()) {
System.out.println(m.group(1));
}
注意 :我不建議這樣做。 正則表達式將更加通用和強大。
String n ="${farsiName} - {symbolName}";
String s[] = n.split(" - ");
for(String x : s){
System.out.println(x.replace("$", "").replace("{", "").replace("}", ""));
}
public static void main(String[] args){
String n ="${farstName} - {symbolName}";
String arr[] = n.split(" - ");
for(String s : arr){
System.out.println(s.replace("$", "").replace("{", "").replace("}", ""));
}
}
使用此代碼。它可以工作。但是我建議使用正則表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.