我有一個像字符串查找令牌定正則表達式
`[email protected]{name},how are you today, location: @{location}, time: @{time}`
一個字符串,我想找到的所有令牌啓動以「@ {」,結尾是「}」。即我的輸出將成爲以下代幣的列表:@ {name},@ {location},@ {time}。或者只是名字,地點,時間。
我有一個像字符串查找令牌定正則表達式
`[email protected]{name},how are you today, location: @{location}, time: @{time}`
一個字符串,我想找到的所有令牌啓動以「@ {」,結尾是「}」。即我的輸出將成爲以下代幣的列表:@ {name},@ {location},@ {time}。或者只是名字,地點,時間。
就算這樣簡單:
@\{(.+?)\}
@
匹配@
字符\{
匹配的{
\}
匹配的}
.
匹配一切+
表示匹配.
至少一次,最多不限次數?
使得+
懶惰,試圖儘可能少的時間越好,所以比賽不會超過}
。嘗試一下here。
而你只需要得到每場比賽的第一組!
Matcher matcher = Pattern.compile("@\\{(.+?)\\}").matcher("[email protected]{name},how are you today, location: @{location}, time: @{time}");
while (matcher.find()) {
System.out.println(matcher.group(1));
}
快,但不太直觀(IMO)的辦法是更換部分.+?
與[^}]+
,這意味着「匹配一切,這不是一個}
多次,你可以」。
您可以嘗試使用正則表達式匹配與圖案@\{(.*?)\}
:
String input = "[email protected]{name},how are you today, location: @{location}, time: @{time}";
String pattern = "@\\{(.*?)\\}";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
System.out.println("match: " + m.group(1));
}
輸出:
match: name
match: location
match: time
演示在這裏:
您可以使用@\{([^\}]*)\}
表達找到您的令牌
集團(0)將返回令牌與@{...}
,組(1)將在括號只返回值
你必須:
Pattern
定義要匹配的模式Matcher
獲得您的字符串像這樣的東西(代碼寫在飛,未選中):
import java.util.regex.*;
// assume that @{...} may contain only letters
// { and } symbols must be \escaped
Pattern p = Pattern.compile("@\\{([a-zA-Z]+)\\}");
Matcher m = p.matcher("[email protected]{name},...");
List<String> matches = new ArrayList<String>();
while (m.find()) {
String x = m.group(1); // returns "name" from "@{name}"
// use group(0) to get the whole "@{name}"
matches.add(x);
}
如果你只是想找到結果,使用正則表達式可能是最快和最簡單的方法。 Java代碼可能是這樣的:
String str="[email protected]{name},how are you today, location: @{location}, time: @{time}";
Pattern pattern = Pattern.compile("@\\{(.*?)\\}");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
還是要弄清楚在你自己的方式,你也可以寫一些簡單的for循環的代碼來解決問題,這是很好的開始由你手寫的學習計劃你自己的代碼,這裏有一個例子:
String str="[email protected]{name},how are you today, location: @{location}, time: @{time}";
String tempStr="";
boolean inBracket=false;
for (int i=0;i<str.length();i++){
if(!inBracket) {
if (i<str.length()-2&&str.charAt(i) == '@'&&str.charAt(i+1) == '{') {
inBracket=true;
i++;
}
}else{
if(str.charAt(i)=='}'){
System.out.println(tempStr);
tempStr="";
inBracket=false;
}else{
tempStr+=str.charAt(i);
}
}
}
輸出:
name
location
time
你嘗試過自己嗎? –