我想在String 之间<和之间找到单词>.
例如:
String str=your mobile number is <A> and username is <B> thanks <C>;
Run Code Online (Sandbox Code Playgroud)
我想A,B,C从字符串.
我试过了
import java.util.regex.*;
public class Main
{
public static void main (String[] args)
{
String example = your mobile number is <A> and username is <B> thanks <C>;
Matcher m = Pattern.compile("\\<([^)]+)\\>").matcher(example);
while(m.find()) {
System.out.println(m.group(1));
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在做什么有什么问题?
用下面的习惯和向后引用获取值你A,B和C占位符:
String example = "your mobile number is <A> and username is <B> thanks <C>";
// ? left delimiter - no need to escape here
// | ? group 1: 1+ of any character, reluctantly quantified
// | | ? right delimiter
// | | |
Matcher m = Pattern.compile("<(.+?)>").matcher(example);
while (m.find()) {
System.out.println(m.group(1));
}
Run Code Online (Sandbox Code Playgroud)
产量
A
B
C
Run Code Online (Sandbox Code Playgroud)
注意
如果您喜欢没有索引后引用和"环顾四周"的解决方案,您可以使用以下代码实现相同的目标:
String example = "your mobile number is <A> and username is <B> thanks <C>";
// ? positive look-behind for left delimiter
// | ? 1+ of any character, reluctantly quantified
// | | ? positive look-ahead for right delimiter
// | | |
Matcher m = Pattern.compile("(?<=<).+?(?=>)").matcher(example);
while (m.find()) {
// no index for back-reference here, catching main group
System.out.println(m.group());
}
Run Code Online (Sandbox Code Playgroud)
我个人觉得后者在这种情况下不太可读.