(警告 - 使用谷歌翻譯制作)
我正在學習使用正則運算式,同時為自己創建一個簡單的程式,該程式將輸入一個字串,該字串由各種擲骰子的公式和它們的修飾符組成。例子:
2d6 13 3d10-1d4 5 1d8-6
我有一個正則運算式來搜索像“ -XdY”這樣的段:
(^|[\\ -])[1-9]\\d*d[1-9]\\d*
我想從字串中剪切這些段,將它們存盤為陣列以供進一步處理,同時將它們從字串中洗掉
Input - string "2d6 13 3d10-1d4 5 1d8-6"
Output - string " 13 5-6" (without any -XdY) and array of strings {"2d6", " 3d10", "-1d4", " 1d8"} (all of -XdY)
所以在那之后它可以用修飾符重復(使用另一個正則運算式)
Input - string " 13 5-6"
Output - string "" and array of strings {" 13", " 5", "-6"}
并且,通過最后的剩余字串,了解資料是否輸入正確(空=好)。
問題是我根本找不到合適的工具來從字串中剪切某些片段并將它們保存為陣列。
你能幫助我嗎?或者也許有一個更簡單的演算法來完成這項任務?
提前感謝您的幫助!
uj5u.com熱心網友回復:
在or之前拆分-:
String[] parts = str.split("(?=[ -])");
測驗代碼:
String str = "2d6 13 3d10-1d4 5 1d8-6";
String[] parts = str.split("(?=[ -])");
System.out.println(Arrays.toString(parts));
輸出:
[2d6, 13, 3d10, -1d4, 5, 1d8, -6]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/531992.html
標籤:爪哇正则表达式细绳
上一篇:如何用ajax計算總結果?
