我想截取出PK20230512063,内容长度不固定,要使用 “-” 来截取
我想的是提取包含 "PK"
字符串的部分,可以使用以下代码:
s = '0601020102004-C073102013-PK20230512063-CD23040100-142'
target_str = ''
for substr in s.split('-'):
if 'PK' in substr:
target_str = substr
break
print(target_str)
let str = "0601020102004-C073102013-PK20230512063CD23040100-142";
let regex = /PK\d{}/g;
let result = str.match(regex)[0];
console.log(result); // 输出 "PK20230512063"
这样试试呢
const str = "0601020102004-C073102013-PK20230512063-CD23040100-142";
const regex = /PK(\d+)-/; // 匹配以PK开头的数字串,直到遇到"-"
const matchResult = str.match(regex);
if (matchResult && matchResult[1]) {
const extractedString = matchResult[1];
console.log(extractedString); // 输出: PK20230512063
} else {
console.log("未找到匹配的子串");
}
如果你要取第二个减号后面的内容,可以
^(?<=\w+\-\w+\-)\w+(?=\-)