我正在尝试解析通过读卡器传递的卡数据,但是,我收到有关正则表达式的错误。我知道这意味着 this.match 为空,但我不确定为什么它为空。有什么建议么? (使用 Angular 9)
CardData: string;
CardPattern = new RegExp("^\%B(\d+)\^(\w+)\/(\w+)\^\d+\?;\d+=(\d\d)(\d\d)\d+$");
CardNumber: string;
FirstName: string;
LastName: string;
ExpData: string;
match: RegExpExecArray;
constructor(private snackbar: SnackBar) {
}
ngOnInit() {
// getaCardData();
this.CardData = "%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?"
this.match = this.CardPattern.exec(this.CardData);
this.CardNumber = this.match[1]
this.FirstName = this.match[3];
this.LastName = this.match[2];
this.ExpData = this.match[5] + "/" +this.match[4];
console.log(this.CardNumber);
}
最佳答案
您的模式不匹配,因为字符串末尾有一个附加字符 ?:
this.CardData = %B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?"
替换为:
this.CardData = "%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111"
或者改变你的模式:
^\%B(\d+)\^(\w+)\/(\w+)\^\d+\?;\d+=(\d\d)(\d\d)\d+\?$
更新:添加了工作代码片段供您引用!尝试添加标志,它应该可以工作。
const regex = new RegExp(/^\%B(\d+)\^(\w+)\/(\w+)\^\d+\?;\d+=(\d\d)(\d\d)\d+\?$/, 'gm');
const input = `%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?`;
var match = regex.exec(input);
document.write(match.length);
关于javascript - 错误类型错误 : Cannot read property '1' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60367448/