[英]Convert this pattern to regex for Pattern.matches(..)
我的某些字符串可能包含类似于@[alph4Num3ric-alph4Num3ric]
的子字符串,在这里我将找到字母数字ID,并将其替换为映射到映射中关联键的对应文本值。
我的第一个倾向是检查我的string.contains("@[")
但我想更具体一点
所以现在我正在查看Pattern.matches(
但不确定正则表达式和总表达式
我如何在Pattern.matches方法中对@ [......-....]进行正则表达式,它还必须考虑破折号。 因此,我不确定在此语法中需要转义哪些内容或使用通配符或更多内容。
我也不是100%知道这是否是最好的信息。 我想首先从Pattern.matches中获取一个布尔值,然后获取真实值并使用这些值修改字符串,这似乎已经足够好了,但是我想减少计算量。
尝试使用此:
/@[(a-zA-Z0-9-)+]/
我没有尝试过,但希望这会有所帮助。 另外,如果返回错误,则在9与-之间添加反斜杠,例如/ @ [(a-zA-Z0-9-)+] /
请尝试一下,
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String expression = "String contains @[alph4Num3ric-alph4Num3ric] as substring";
Pattern pattern = Pattern
.compile("\\@\\[([a-zA-Z0-9]+)-([a-zA-Z0-9]+)\\]");
Matcher matcher = pattern.matcher(expression);
while (matcher.find()) {
System.out.println("matched: "+matcher.group());
System.out.println("group1: "+matcher.group(1));
System.out.println("group2: "+matcher.group(2));
System.out
.println("after replace "+expression.replace(matcher.group(1), "customkey"));
}
}
}
输出:
matched: @[alph4Num3ric-alph4Num3ric]
group1: alph4Num3ric
group2: alph4Num3ric
after replace: String contains @[customkey-customkey] as substring
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.