java中匹配字符串所需的正则表达式模式以';{{';并以“}}”结尾;
嗨, 我需要创建一个正则表达式模式,该模式将拾取以“{{”开头并以“{”结尾的匹配字符串 来自给定字符串的“}}”java中匹配字符串所需的正则表达式模式以';{{';并以“}}”结尾;,java,regex,Java,Regex,嗨, 我需要创建一个正则表达式模式,该模式将拾取以“{{”开头并以“{”结尾的匹配字符串 来自给定字符串的“}}” The pattern I have created is working same with the strings starting with '{{{' and '{{', Similarly with ending with '}}}' and “}}” Output of above code: matches = {{phone2}} matches = {{phon
The pattern I have created is working same with the strings starting with '{{{' and '{{', Similarly with ending with '}}}' and
“}}”
Output of above code:
matches = {{phone2}}
matches = {{phone3}}
matches = {{phone5}}
**Expected Output**:
matches = {{phone5}}
I need only Strings which follows two consecutive pattern of '{' and '}' not three.
分享下面的代码
package com.test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
public static void main(String[] args) {
String text = "<test>{{#phone1}}<a href=\"tel:{{{phone2}}}\">{{{phone3}}}</a>{{/phone4}} {{phone5}}></test>";
//String pattern = "\\{\\{\\s*?(\\w*?)\\s*?(?!.*\\}\\}\\}$)";
String pattern = "\\{\\{\\s*?(\\w*?)\\s*?}}";
Pattern placeholderPattern = Pattern.compile(pattern);
Matcher placeholderMatcher = placeholderPattern.matcher(text);
while (placeholderMatcher.find()) {
System.out.println("matches = " + placeholderMatcher.group());
}
}
}
包com.test;
导入java.util.regex.Matcher;
导入java.util.regex.Pattern;
公共类RegexTest{
公共静态void main(字符串[]args){
String text=“{{phone1}}{{/phone4}}{{phone5}}>”;
//字符串模式=“\\{\\s*?(\\w*?)\\s*?(?!!\\\\\}\\\\}$)”;
字符串模式=“\\{\\{\\s*?(\\w*?)\\s*?}”;
Pattern占位符Pattern=Pattern.compile(Pattern);
匹配器占位符匹配器=占位符模式.Matcher(文本);
while(placeholderMatcher.find()){
System.out.println(“matches=“+placeholderMatcher.group());
}
}
}
您可以使用
String pattern = "(?<!\\{)\\{{2}\\s*(\\w*)\\s*\\}{2}(?!\\})";
看
详细信息
(?-如果在当前位置的左侧有一个
字符,则反向查找将导致匹配失败{
-{{2}
子字符串{{
-0+空格\s*
-第1组:一个或多个单词字符(如果使用了(\w*)
量词,则为1个或多个)+
-0+空格\s*
-\}{2}
字符串}
-如果当前位置右侧有一个(?!\})
字符,则会导致匹配失败的负前瞻}
**预期输出**:matches={{phone5}}不,有问题非常感谢,String pattern=“(?完成。再次感谢。
String pattern = "(?<!\\{)\\{{2}\\s*(\\w+)\\s*\\}{2}(?!\\})";
String text = "<test>{{#phone1}}<a href=\"tel:{{{phone2}}}\">{{{phone3}}}</a>{{/phone4}} {{phone5}}></test>";
String pattern = "(?<!\\{)\\{{2}\\s*(\\w*)\\s*\\}{2}(?!\\})";
Pattern placeholderPattern = Pattern.compile(pattern);
Matcher placeholderMatcher = placeholderPattern.matcher(text);
while (placeholderMatcher.find()) {
System.out.println("Match: " + placeholderMatcher.group());
System.out.println("Group 1: " + placeholderMatcher.group(1));
}
Match: {{phone5}}
Group 1: phone5