我正在嘗試將用戶命令解釋為破折號可選標志。
{run -o -f -a file1 file2}
像這樣的東西:
/{run (-o|-f) (\w ) (. ?)}/g;
非常有限,只有 1 個標志選擇。
我正在尋找一個正則運算式,它可以正確地決議帶有任意數量的破折號標志的字串,將標志分成組,而不用擔心中間的一定數量的空白。
string = "{run -a file1 file2}"
string = "{run -a -o -f file1 file2}"
string = "{run -f-a-o file1 file2}"
string.match(regex) 應該輸出每個標志和每個檔案名。
示例輸出為:
["f", "a", "o", "file1", "file2"]
或者如果不可能,像這樣:?
["-f-a-o", "file1", "file2"]
uj5u.com熱心網友回復:
單個正則運算式能夠捕獲最多 9 個組。
因此...... “使用任意數量的破折號標志決議 [ing] 字串” ......就像 OP 確實要求不能僅通過單個正則運算式來實作。
一個足夠好的方法是捕獲兩個組,flags序列和files序列,然后將它們處理成分離的標志和檔案名專案的串聯串列......
// see ... [https://regex101.com/r/VFjeK1/1]
const regXFlagsAndFiles =
(/^\{\s*run(?:\s -(?<flags>[a-z] (?:\s*-[a-z] )*))*\s (?<files>[\w.] (?:\s [\w.] )*)\s*\}$/);
function parseFlagAndFileList(value) {
const {
flags,
files,
} = regXFlagsAndFiles
.exec(String(value))
?.groups || {};
return (flags
?.split(/\s*-\s*/)
?? []
).concat(
files
?.split(/\s /)
?? []
);
}
console.log([
'{run file1 file2}',
'{run -a file1 file2}',
'{run -a -o -f file1 file2}',
'{run -f-a-o file1 file2}',
].map(parseFlagAndFileList));
console.log([
'{run}',
'{run }',
'{run file1 }',
'{run -abc file1.foo file2.bar }',
'{run -ab -ogg -fgg file1.baz file2 }',
'{run -f-a-ob file1 file2.biz }',
'{ run -a -b }',
'{ fun -a -b }',
].map(parseFlagAndFileList));
.as-console-wrapper { min-height: 100%!important; top: 0; }
一個正則運算式幾乎涵蓋了 OP 只用一個簡單模式完成所有操作的愿望,看起來像這樣/[\w.] /g......
它的原因...
- 根本不包括驗證,
- 并且需要得到...的支持
String.prototype.match和Array.prototype.slice.
// see ... [https://regex101.com/r/VFjeK1/3]
const regXCommandTokens = (/[\w.] /g);
console.log([
'{run file1 file2}',
'{run -a file1 file2}',
'{run -a -o -f file1 file2}',
'{run -f-a-o file1 file2}',
].map(command => command.match(regXCommandTokens).slice(1)));
console.log([
'{run}',
'{run }',
'{run file1 }',
'{run -abc file1.foo file2.bar }',
'{run -ab -ogg -fgg file1.baz file2 }',
'{run -f-a-ob file1 file2.biz }',
'{ run -a -b }',
'{ fun -a -b }',
].map(command => command.match(regXCommandTokens).slice(1)));
.as-console-wrapper { min-height: 100%!important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/416619.html
標籤:
