![](/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.