![](/img/trans.png)
[英]Given a number N and an array of N strings, sort the strings based on number of vowels in each of the strings in the descending order
[英]add +n to the name of some Strings id ends with “v + number”
我有一个字符串数组
Value[0] = "Documento v1.docx";
Value[1] = "Some_things.pdf";
Value[2] = "Cosasv12.doc";
Value[3] = "Document16.docx";
Value[4] = "Nodoc";
我想更改文档的名称,并将+1添加到每个文档的版本中。 但是,只有以v {number}结尾的文档字符串(v1,v12等)。
我使用了正则表达式[v]+a*^
但只有我获得了“ v”,而不是“ v”之后的数字
正则表达式v\\d+
应与字母v
匹配,后跟数字(请注意,将其分配给字符串时,可能需要将其写为v\\\\d+
)。 正则表达式的进一步增强取决于代码的外观。 您可能希望将捕获组包装为(v\\d+)
或什至(v(\\d+))
。
快速搜索出现的第一个参考是https://docs.oracle.com/javase/tutorial/essential/regex/ ,这应该是一个很好的起点。
如果要处理所有以v
+ digits +扩展名结尾的字符串,请使用v(\\\\d+)(?=\\\\.[^.]+$)
,然后在Matcher#appendReplacement
操纵Group 1的值Matcher#appendReplacement
方法:
String[] strs = { "Documento v1.docx", "Some_things.pdf", "Cosasv12.doc", "Document16.docx", "Nodoc"};
Pattern pat = Pattern.compile("v(\\d+)(?=\\.[^.]+$)");
for (String s: strs) {
StringBuffer result = new StringBuffer();
Matcher m = pat.matcher(s);
while (m.find()) {
int n = 1 + Integer.parseInt(m.group(1));
m.appendReplacement(result, "v" + n);
}
m.appendTail(result);
System.out.println(result.toString());
}
参见Java演示
输出:
Documento v2.docx
Some_things.pdf
Cosasv13.doc
Document16.docx
Nodoc
图案细节
v
- v
(\\d+)
-组1值:一位或多位数字 (?=\\.[^.]+$)
-后面跟一个文字.
然后再加上1个以上的字符.
直到字符串的末尾。 尝试这样的正则表达式:
([v])([1-9]{1,3})(\.)
请注意,为了减少“冲突”和最多999个版本({1,3}),我已经包括了该点。
另外,我使用了3个不同的组,以便您可以轻松地检索版本号,增加它并替换字符串。
例:
String regex = ;
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(time);
if(matcher.matches()){
int version = matcher.group(2); // don't remember if is 0 or 1 based
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.