错误TypeError:无法读取null的属性“ 1”

时间:2020-02-23 22:23:04

标签: javascript angular typescript

我正在尝试解析通过读卡器传递的卡数据,但是,我在正则表达式方面遇到了错误。我了解这意味着this.match为null,但是我不确定为什么为null。有什么建议? (使用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);
    }

2 个答案:

答案 0 :(得分:1)

您的模式不匹配,因为字符串末尾还有一个附加字符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);

答案 1 :(得分:0)

似乎与转义符有关。我已经尝试过运行以下两行的Chrome Developer工具。

1. Without Template Literal
new RegExp("^\%B(\d+)\^(\w+)\/(\w+)\^\d+\?;\d+=(\d\d)(\d\d)\d+$").exec('%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?')

result: null

2. With Template Literal
new RegExp($`{"^\%B(\d+)\^(\w+)\/(\w+)\^\d+\?;\d+=(\d\d)(\d\d)\d+$"}`).exec('%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?')

result: ["O", index: 20, input: "%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?", groups: undefined]

将您的Regex表达式包装在Template Literal中应该可以解决此问题。编译过程可能在构建过程中考虑了通配符,这说明了为什么在编译后仍然可以工作。