英文:
How to extract content from sign using regex in Java?
问题
你的代码中有一些问题。以下是修正后的代码:
static java.util.regex.Pattern p1=java.util.regex.Pattern.compile("\$\\{\\w+\\}");
private static String getStudentName(String expression) {
StringBuffer stringBuffer = new StringBuffer();
java.util.regex.Matcher m1 = p1.matcher(expression);
while(m1.find()) {
String param = m1.group();
stringBuffer.append(param.substring(2, param.indexOf('.')) + ",");
}
if(stringBuffer.length() > 0){
return stringBuffer.deleteCharAt(stringBuffer.length() - 1).toString();
}
return null;
}
注意到我已经更新了正则表达式和 param
的提取方式,以及对 substring
的调用,以确保能正确提取出 studentA
和 studentB
。
英文:
My content is a string like this:whoad123@@${studentA.math1.math2}dsafddasfd${studentB.math2.math3}
,now I want to extract the content studentA,studentB
which is in the braces and before the first pot(${**}).What's wrong with my code?
static java.util.regex.Pattern p1=java.util.regex.Pattern.compile("\\*\$\\{\\w+\\}");
private static String getStudentName(String expression) {
StringBuffer stringBuffer = new StringBuffer();
java.util.regex.Matcher m1= p1.matcher(expression);
while(m1.find()) {
String param=m1.group(1);
stringBuffer.append(param.substring(2,param.indexOf("\\.")) + ",");
}
if(stringBuffer.length()>0){
return stringBuffer.deleteCharAt(stringBuffer.length()-1).toString();
}
return null;
}
答案1
得分: 1
Use
${([^{}.]+)
See proof
Declare in Java as
static java.util.regex.Pattern p1=java.util.regex.Pattern.compile("\$\\{([^{}.]+)");
英文:
Use
$\{([^{}.]+)
See proof
Declare in Java as
static java.util.regex.Pattern p1=java.util.regex.Pattern.compile("\$\\{([^{}.]+)");
EXPLANATION
EXPLANATION
--------------------------------------------------------------------------------
$ '$'
--------------------------------------------------------------------------------
\{ '{'
--------------------------------------------------------------------------------
( group and capture to :
--------------------------------------------------------------------------------
[^{}.]+ any character except: '{', '}', '.' (1
or more times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of
答案2
得分: 1
public static String getStudentName(String expression) {
Pattern pattern = Pattern.compile("\\{(?<student>\\w+)\\.[^\\}]+\\}");
Matcher matcher = pattern.matcher(expression);
List<String> names = new ArrayList<>();
while (matcher.find()) {
names.add(matcher.group("student"));
}
return String.join(",", names);
}
See demo in [regex101.com][1]
英文:
public static String getStudentName(String expression) {
Pattern pattern = Pattern.compile("\\{(?<student>\\w+)\\.[^\\}]+\\}");
Matcher matcher = pattern.matcher(expression);
List<String> names = new ArrayList<>();
while (matcher.find()) {
names.add(matcher.group("student"));
}
return String.join(",", names);
}
See demo in regex101.com
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论