這是我需要什么正則運算式的示例
我在一個檔案中有很多這樣的行
build test/testfoo/CMakeFiles/testfoo2.dir/testfoo2.cpp.o: CXX_COMPILER__testfoo2_Debug /home/juxeii/projects/gtest-cmake-example/test/testfoo/testfoo2.cpp || cmake_object_order_depends_target_testfoo2
我需要檢測 和 之間的字串CXX_COMPILER__,_Debug這里是testfoo2。
同時,我還需要檢測整個檔案路徑/home/juxeii/projects/gtest-cmake-example/test/testfoo/testfoo2.cpp,它總是在第一次匹配之后出現。
我想不出一個正則運算式。到目前為止.*CXX_COMPILER__(.\w )_\w |(\/[a-zA-Z_0-9-] ) \.\w ,我已經在 typescript 中使用它,如下所示:
const fileAndTargetRegExp = new RegExp('.*CXX_COMPILER__(.\w )_\w |(\/[a-zA-Z_0-9-] ) \.\w ', 'gm');
let match;
while (match = fileAndTargetRegExp.exec(fileContents)) {
//do something
}
但我沒有匹配。是否有捷徑可尋?
uj5u.com熱心網友回復:
看起來不錯,但你需要分隔符。在您的正則運算式之前和之后添加“/” - 沒有引號。
let fileContents = 'build test/testfoo/CMakeFiles/testfoo2.dir/testfoo2.cpp.o: CXX_COMPILER__testfoo2_Debug /home/juxeii/projects/gtest-cmake-example/test/testfoo/testfoo2.cpp || cmake_object_order_depends_target_testfoo2';
const fileAndTargetRegExp = new RegExp(/.*CXX_COMPILER__(.\w )_\w |(\/[a-zA-Z_0-9-] ) \.\w /, 'gm');
let match;
while (match = fileAndTargetRegExp.exec(fileContents)) {
console.log(match);
}
uj5u.com熱心網友回復:
它總是 || <stuff here>在最后嗎?如果是這樣,這個基于您提供的正則運算式應該可以作業:
/.*CXX_COMPILER__(\w )_. ?((?:\/. ) ) \|\|.*/g
正如regex101 分解所示,第一個捕獲組應該包含 and 之間的字串CXX_COMPILER__,_Debug而第二個應該包含路徑,使用空格和管道來檢測后者的結束位置。
let line = 'build test/testfoo/CMakeFiles/testfoo2.dir/testfoo2.cpp.o: CXX_COMPILER__testfoo2_Debug /home/juxeii/projects/gtest-cmake-example/test/testfoo/testfoo2.cpp || cmake_object_order_depends_target_testfoo2';
const matches = line.match(/.*CXX_COMPILER__(\w )_. ?((?:\/. ) ) \|\|.*/).slice(1); //slice(1) just to not include the first complete match returned by match!
for (let match of matches) {
console.log(match);
}
如果管道并不總是在那里,那么這個版本應該可以代替(regex101):
.*CXX_COMPILER__(\w )_. ?((?:\/(?:\w|\.|-) ) ).*
但它要求您每次意識到可能存在一個新路徑字符時單獨添加所有有效路徑字符,并且您需要確保路徑沒有空格,因為向正則運算式添加空格會使其檢測到路徑之后的東西也是如此。
uj5u.com熱心網友回復:
這是我使用replace的方法:
我需要檢測CXX_COMPILER__和_Debug之間的字串,這里是testfoo2。
嘗試將字串的所有字符僅替換$1為介于CXX_COMPILER__和之間的第一個捕獲組_Debug:
/.*CXX_COMPILER__(\w )_Debug.*/
^^^^<--testfoo2
我還需要檢測整個檔案路徑 /home/juxeii/projects/gtest-cmake-example/test/testfoo/testfoo2.cpp
同樣,只是這次 replace all 離開第二個匹配的組,這是我們第一個捕獲的組之后的任何內容:
/.*CXX_COMPILER__(\w )_Debug\s (.*?)(?=\\|\|).*/
^^^<-- /home/.../testfoo2.cpp
let line = 'build test/testfoo/CMakeFiles/testfoo2.dir/testfoo2.cpp.o: CXX_COMPILER__testfoo2_Debug /home/juxeii/projects/gtest-cmake-example/test/testfoo/testfoo2.cpp || cmake_object_order_depends_target_testfoo2'
console.log(line.replace(/.*CXX_COMPILER__(\w )_Debug.*/gm,'$1'))
console.log(line.replace(/.*CXX_COMPILER__(\w )_Debug\s (.*?)(?=\\|\|).*/gm,'$2'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/466177.html
標籤:javascript 正则表达式 打字稿 文件路径
上一篇:從物件陣列中提取值?
