简体   繁体   中英

ERROR TypeError: Cannot read property '1' of null

I am trying to parse card data that is passed through a card reader, however, I am getting an error in regards to the regex. I understand it means that this.match is null but I am not sure why it is null. Any suggestions? (Using 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);
    }

Your pattern does not match because you have an additional character ? at the end of your string: this.CardData = %B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111?"

Replace it with:

this.CardData = "%B6545461234613451^DOE/JOHN^00000000000000000000000?;6545461234613451=984651465116111"

or change your pattern instead with: ^\\%B(\\d+)\\^(\\w+)\\/(\\w+)\\^\\d+\\?;\\d+=(\\d\\d)(\\d\\d)\\d+\\?$

Update: Added working code snippet for you reference! Try adding flags and it should work.

 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);

It seems that it has something to do with escape character. I have tried on Chrome Developer tools running the following two lines.

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]

Wrapping your Regex expression in a Template Literal should solve the problem. The compile process has likely took the wild card characters into account during the build, which suggests why it works after compilation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM