[英]Adding onto a java.util.regex.Pattern or Merging Them
I'm holding filename format data in a Pattern
object. 我在Pattern
对象中保存文件名格式数据。 For example: _\\\\d+x\\\\d+\\\\.png
. 例如: _\\\\d+x\\\\d+\\\\.png
。 In my setup, this would denote icons of different sizes (eg icon_16x16.png
, icon_48x48.png
and so on). 在我的设置中,这将表示不同大小的图标(例如icon_16x16.png
, icon_48x48.png
等)。
I have a method that compares an actual filename with the given pattern; 我有一个方法,将实际文件名与给定的模式进行比较; however, a base name must also be provided (in my example, this would be "icon"): 但是,还必须提供基本名称(在我的示例中,这将是“icon”):
public boolean matches(String filename, String baseName) {
if (!IOCase.SYSTEM.checkStartsWith(filename, baseName)) {
return false;
}
return format.matcher(filename.replaceFirst(baseName, "")).matches();
}
What I'm doing here is first checking if filename
starts with the base name. 我在这里做的是首先检查filename
是否以基本名称开头。 If so, the base name is stripped from the filename string so that it can be compared with the Pattern
object ( format
). 如果是这样,则从文件名字符串中删除基本名称,以便可以将其与Pattern
对象( format
)进行比较。
I know I could do return filename.matches(Pattern.quote(baseName) + format.pattern())
, but I'm wondering if there's a better, hopefully more programmatic way of doing this. 我知道我可以return filename.matches(Pattern.quote(baseName) + format.pattern())
,但我想知道是否有更好的,希望更有编程的方式来做到这一点。
To be precise, I want to know if it's possible to add onto a java.util.regex.Pattern
or merge two of them without dealing with their underlying string representations. 确切地说,我想知道是否可以添加到 java.util.regex.Pattern
或合并其中两个而不处理它们的基础字符串表示。
No, you cannot modify a compiled Pattern
. 不,您无法修改已编译的Pattern
。 You could create a new Pattern
by combining the regex strings and calling Pattern.compile()
again. 您可以通过组合正则表达式字符串并再次调用Pattern.compile()
来创建新Pattern
。
Find below a sample code using pattern/matcher/group without any string manipulation: 使用pattern / matcher / group查找下面的示例代码,不需要任何字符串操作:
If prefix is word chars only 如果前缀只是单词字符
Pattern p = Pattern.compile("(\\w+)(_\\d+x\\d+\\.png)");
Matcher m = p.matcher("icon1_16x16.png");
String baseName = "icon";
//If match found, m.group(1) returns the prefix of `_..x..png`
if(m.find() && baseName.equals(m.group(1))){
System.out.println("Match Found");
}else{
System.out.println("Match Not Found");
}
If prefix can be any character, then use regex as (.+)(_\\\\d+x\\\\d+\\\\.png)
如果前缀可以是任何字符,则使用正则表达式作为(.+)(_\\\\d+x\\\\d+\\\\.png)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.