[英]add +n to the name of some Strings id ends with “v + number”
I have an array of Strings 我有一个字符串数组
Value[0] = "Documento v1.docx";
Value[1] = "Some_things.pdf";
Value[2] = "Cosasv12.doc";
Value[3] = "Document16.docx";
Value[4] = "Nodoc";
I want to change the name of the document and add +1 to the version of every document. 我想更改文档的名称,并将+1添加到每个文档的版本中。 But only the Strings of documents that ends with v{number} (v1, v12, etc).
但是,只有以v {number}结尾的文档字符串(v1,v12等)。
I used the regex [v]+a*^
but only i obtain the "v" and not the number after the "v" 我使用了正则表达式
[v]+a*^
但只有我获得了“ v”,而不是“ v”之后的数字
The Regex v\\d+
should match on the letter v
, followed by a number (please note that you may need to write it as v\\\\d+
when assigning it to a String). 正则表达式
v\\d+
应与字母v
匹配,后跟数字(请注意,将其分配给字符串时,可能需要将其写为v\\\\d+
)。 Further enhancement of the Regex depends in what your code looks like. 正则表达式的进一步增强取决于代码的外观。 You may want to to wrap in a Capturing Group like
(v\\d+)
, or even (v(\\d+))
. 您可能希望将捕获组包装为
(v\\d+)
或什至(v(\\d+))
。
The first reference a quick search turns up is https://docs.oracle.com/javase/tutorial/essential/regex/ , which should be a good starting point. 快速搜索出现的第一个参考是https://docs.oracle.com/javase/tutorial/essential/regex/ ,这应该是一个很好的起点。
If all your strings ending with v
+ digits + extension are to be processed, use a pattern like v(\\\\d+)(?=\\\\.[^.]+$)
and then manipulate the value of Group 1 inside the Matcher#appendReplacement
method: 如果要处理所有以
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());
}
Output: 输出:
Documento v2.docx
Some_things.pdf
Cosasv13.doc
Document16.docx
Nodoc
Pattern details 图案细节
v
- a v
v
- v
(\\d+)
- Group 1 value: one or more digits (\\d+)
-组1值:一位或多位数字 (?=\\.[^.]+$)
- that are followed with a literal .
(?=\\.[^.]+$)
-后面跟一个文字.
and then 1+ chars other than .
.
up to the end of the string. Try a regex like this: 尝试这样的正则表达式:
([v])([1-9]{1,3})(\.)
notice that I've already included the point in order to have less "collisions" and a maximum of 999 versions({1,3}). 请注意,为了减少“冲突”和最多999个版本({1,3}),我已经包括了该点。
Further more I've used 3 different groups so that you can easily retrieve the version number increase it and replace the string. 另外,我使用了3个不同的组,以便您可以轻松地检索版本号,增加它并替换字符串。
Example: 例:
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.