Home > Software design >  Regex of dynamic block of characters
Regex of dynamic block of characters

Time:08-24

I have a block of number characters separated by '=' and the number range can be always different on both sides. Example: 12345678999999=654784651321, next time it could be: 4567894135=456789211

I need help with finding suitable regex which select me always numbers between first 6 and last 4 digits of left side of block and then all numbers after 7th digit of right side of block:

123456[][][][]9999=6547846[][][][][]

Is this somehow possible?

CodePudding user response:

[0-9]{6}([0-9]*)[0-9]{4}=[0-9]{7}([0-9]*)

CodePudding user response:

Assuming the difficulty isn't matching a continuous set of digits, but rather matches each digit seperately try:

(?:^\d{6}|=\d{7}|\G)(?=\d{5,8}=|\d*$)\K\d

See an online demo

  • (?: - Open non-capture group for alternation;
    • ^\d{6} - Match start-line anchor followed by 6 digits;
    • | - Or;
    • =\d{7} - Match a literal '=' followed by exactly 7 digits;
    • | - Or;
    • \G - Assert position at end of previous match or start of string;
  • (?=\d{5,8}=|\d*$) - Positive lookahead to assert possition is followed by either 5-8 digits upto an '=' or 0 (greedy) digits upto end-line anchor;
  • \K - Reset starting point of previous reported match;
  • \d - A single digit.

Alternatively, if you have an environment that supports zero-width lookbehind like JavaScript or PyPi's regex package in Python, try:

(?:(?=\d{5,8}=)(?<=\d{6})|(?<==\d{7,}))\d

See an online demo

  • (?: - Open non-capture group for alternation;
    • (?=\d{5,8}=)(?<=\d{6}) - Positive lookahead to assert position is followed by 5-8 digits and an '=' but also preceded by at least 6 digits;
    • | - Or;
    • (?<==\d{7,}) - Positive lookbehind to assert position is preceded by an '=' followed by 7 digits;
  • \d - A single digit.

CodePudding user response:

//    6   NOT number or =      
//    ||                     
//    \/                 
/[0-9]{6}[^\=0-9]*\=[^\=0-9]*[0-9]{4}/
  • Related