FHEM Forum

FHEM => Automatisierung => Perl für FHEM-User => Thema gestartet von: doc. am 10 Oktober 2024, 20:06:36

Titel: Hilfe beim Escapen einer RegEx
Beitrag von: doc. am 10 Oktober 2024, 20:06:36
Hi zusammen,

ich mache jetzt schon Stunden an dieser Herausforderung rum:

$outputBMW =~ (?<=mileage\": \[ )(\d*)(?=, \"km);
Wenn ich das so lasse, wie aus dem RegEx101, dann kommt natürlich

Unterminated <> operator at ./FHEM/99_myUtils.pm
Nächster Schritt, escapen von < und ?:

$outputBMW =~ (/?/<=mileage\": \[ )(\d*)(/?=, \"km)
bringt:

Quantifier follows nothing in regex; marked by <-- HERE in m/? <-- HERE / at ./FHEM/99_myUtils.pm
Und dann hänge ich...weiß irgendjemand, welche Zeichen ich noch in irgendeiner Form escapen muss? Ich hab schon zig verschiedene Kombinationen durchprobiert, ich komme immer wieder bei der gleichen Fehlermeldung raus...

Titel: Aw: Hilfe beim Escapen einer RegEx
Beitrag von: betateilchen am 10 Oktober 2024, 20:24:59
Zeig doch mal die Daten, aus denen Du etwas extrahieren möchtest.
Es würde die Hilfestellung erheblich vereinfachen.

Spontan würde ich sagen, Deine Syntax im perl Code ist einfach falsch.

Müsste es nicht

=~ m/.../;
oder so ähnlich heissen?
Titel: Aw: Hilfe beim Escapen einer RegEx
Beitrag von: doc. am 10 Oktober 2024, 20:28:54
Das ist die relevante Stelle:

, "mileage": [ 155275, "km" ],
Ich möchte den Kilometerstand extrahieren.

Inzwischen habe ich die RegEx etwas gekürzt und *alles* escaped was nach Sonderzeichen aussieht, mein aktueller Stand sieht so aus:

$outputBMW =~ /(/?/</=mileage/\/"/: /\/[ /)/\d/*;
Was jetzt zur FM
Unmatched ( in regex; marked by <-- HERE in m/( <-- HERE / at ./FHEM/99_myUtils.pmführt...
Titel: Aw: Hilfe beim Escapen einer RegEx
Beitrag von: Christoph Morrison am 10 Oktober 2024, 20:33:13
Warum parst du das JSON nicht einfach mit einem JSON-Parser, wenn du schon welches bekommst?
Titel: Aw: Hilfe beim Escapen einer RegEx
Beitrag von: doc. am 10 Oktober 2024, 20:44:32
Weil das so aussieht:

Found 1 vehicles: 530d xDrive
VIN:
Mileage: 155275 km
Vehicle data:
[
    {
        "data": {
            "attributes": {
                "model": "530d xDrive",
                "year": 2021,
                "color": 4284900966,
                "brand": "BMW",
                "driveTrain": "MILD_HYBRID",
                "headUnitType": "MGU",
                "headUnitRaw": "HU_MGU",
                "hmiVersion": "ID7",
                "softwareVersionCurrent": {
                    "puStep": {
                        "month": 7,
                        "year": 21
                    },
                    "iStep": 550,
                    "seriesCluster": "S15A"
                },
                "softwareVersionExFactory": {
                    "puStep": {
                        "month": 7,
                        "year": 21
                    },
                    "iStep": 520,
                    "seriesCluster": "S15A"
                },
                "telematicsUnit": "ATM2",
                "bodyType": "G31",
                "countryOfOrigin": "DE",
                "driverGuideInfo": {
                    "androidAppScheme": "com.bmwgroup.driversguide.row",
                    "iosAppScheme": "bmwdriversguide:///open",
                    "androidStoreUrl": "https://play.google.com/store/apps/details?id=com.bmwgroup.driversguide.row",
                    "iosStoreUrl": "https://apps.apple.com/de/app/id714042749?mt=8"
                }
            },
            "capabilities": {
                "remoteServices": {
                    "departureTimerControl": {
                        "id": "departureTimerControl",
                        "state": "NOT_AVAILABLE",
                        "executionApi": "RS_API_V5"
                    },
                    "inCarCamera": {
                        "id": "inCarCamera",
                        "state": "NOT_AVAILABLE",
                        "executionApi": "RS_360_V4"
                    },
                    "inCarCameraDwa": {
                        "id": "inCarCameraDwa",
                        "state": "NOT_AVAILABLE",
                        "executionApi": "RS_360_V4"
                    },
                    "remote360": {
                        "id": "remote360",
                        "state": "NOT_AVAILABLE",
                        "executionApi": "RS_360_V4"
                    },
                    "surroundViewRecorder": {
                        "id": "surroundViewRecorder",
                        "state": "NOT_AVAILABLE",
                        "executionApi": "RS_360_V4"
                    },
                    "windowControl": {
                        "id": "windowControl",
                        "state": "NOT_AVAILABLE",
                        "executionApi": "RS_API_V5"
                    },
                    "centralLockControl": {
                        "id": "centralLockControl",
                        "state": "NOT_AVAILABLE",
                        "executionApi": "RS_API_V5"
                    },
                    "batteryPreconditioningControl": {
                        "id": "batteryPreconditioningControl",
                        "state": "NOT_AVAILABLE",
                        "executionApi": "RS_API_V5"
                    },
                    "doorLock": {
                        "id": "doorLock",
                        "state": "ACTIVATED",
                        "executionApi": "RS_API_V5"
                    },
                    "doorUnlock": {
                        "id": "doorUnlock",
                        "state": "ACTIVATED",
                        "executionApi": "RS_API_V5"
                    },
                    "hornBlow": {
                        "id": "hornBlow",
                        "state": "ACTIVATED",
                        "executionApi": "RS_API_V5"
                    },
                    "lightFlash": {
                        "id": "lightFlash",
                        "state": "ACTIVATED",
                        "executionApi": "RS_API_V5"
                    },
                    "telematicsWakeup": {
                        "id": "telematicsWakeup",
                        "state": "NOT_AVAILABLE",
                        "executionApi": "RS_API_V5"
                    },
                    "wakeup": {
                        "id": "wakeup",
                        "state": "NOT_AVAILABLE",
                        "executionApi": "RS_API_V5"
                    },
                    "interiorPreconditioningControl": {
                        "id": "interiorPreconditioningControl",
                        "state": "NOT_AVAILABLE",
                        "executionApi": "RS_API_V5"
                    }
                },
                "a4aType": "NOT_SUPPORTED",
                "climateNow": true,
                "isClimateTimerSupported": true,
                "climateTimerTrigger": "DEPARTURE_TIMER",
                "isClimateTimerWeeklyActive": true,
                "climateFunction": "VENTILATION",
                "horn": true,
                "isBmwChargingSupported": false,
                "isCarSharingSupported": false,
                "isChargeNowForBusinessSupported": false,
                "isChargingHistorySupported": false,
                "isLocationBasedChargingSettingsSupported": false,
                "isChargingHospitalityEnabled": false,
                "isChargingLoudnessEnabled": false,
                "isChargingPlanSupported": false,
                "isChargingPowerLimitEnabled": false,
                "isChargingSettingsEnabled": false,
                "isBatteryPreconditioningSupported": false,
                "isChargingTargetSocEnabled": false,
                "isCustomerEsimSupported": false,
                "isDataPrivacyEnabled": false,
                "isDCSContractManagementSupported": false,
                "isEasyChargeEnabled": false,
                "isMiniChargingSupported": false,
                "isEvGoChargingSupported": false,
                "isRemoteHistoryDeletionSupported": false,
                "isRemoteEngineStartSupported": false,
                "isRemoteServicesActivationRequired": false,
                "isRemoteServicesBookingRequired": false,
                "isScanAndChargeSupported": false,
                "lastStateCallState": "ACTIVATED",
                "lights": true,
                "lock": true,
                "remoteSoftwareUpgrade": true,
                "sendPoi": true,
                "speechThirdPartyAlexa": true,
                "speechThirdPartyAlexaSDK": false,
                "unlock": true,
                "vehicleFinder": true,
                "vehicleStateSource": "LAST_STATE_CALL",
                "isRemoteHistorySupported": true,
                "isWifiHotspotServiceSupported": true,
                "isNonLscFeatureEnabled": false,
                "isSustainabilitySupported": true,
                "isSustainabilityAccumulatedViewEnabled": true,
                "specialThemeSupport": [],
                "isRemoteParkingSupported": false,
                "isRemoteParkingEes25Active": false,
                "remoteChargingCommands": {},
                "digitalKey": {
                    "state": "NOT_AVAILABLE",
                    "bookedServicePackage": "NONE",
                    "vehicleSoftwareUpgradeRequired": false,
                    "isDigitalKeyFirstSupported": false
                },
                "isPersonalPictureUploadSupported": false,
                "personalPictureUpload": {
                    "state": "NOT_AVAILABLE",
                    "aspectRatio": "2:1"
                },
                "isPlugAndChargeSupported": false,
                "isOptimizedChargingSupported": false,
                "alarmSystem": false,
                "isThirdPartyAppStoreSupported": false,
                "thirdPartyAppStore": {
                    "state": "NOT_AVAILABLE"
                },
                "locationBasedCommerceFeatures": {
                    "parking": true,
                    "fueling": false,
                    "reservations": false
                }
            },
            "state": {
                "isLeftSteering": true,
                "lastFetched": "2024-10-10T15:47:22.762Z",
                "lastUpdatedAt": "2024-10-08T20:38:43Z",
                "isLscSupported": true,
                "range": 215,
                "doorsState": {
                    "combinedSecurityState": "UNLOCKED",
                    "leftFront": "CLOSED",
                    "leftRear": "CLOSED",
                    "rightFront": "CLOSED",
                    "rightRear": "CLOSED",
                    "combinedState": "CLOSED",
                    "hood": "CLOSED",
                    "trunk": "CLOSED"
                },
                "windowsState": {
                    "leftFront": "CLOSED",
                    "leftRear": "CLOSED",
                    "rightFront": "CLOSED",
                    "rightRear": "CLOSED",
                    "rear": "CLOSED",
                    "combinedState": "CLOSED"
                },
                "roofState": {
                    "roofState": "CLOSED",
                    "roofStateType": "SUN_ROOF"
                },
                "tireState": {
                    "frontLeft": {
                        "status": {
                            "currentPressure": 290,
                            "targetPressure": 300
                        }
                    },
                    "frontRight": {
                        "status": {
                            "currentPressure": 300,
                            "targetPressure": 300
                        }
                    },
                    "rearLeft": {
                        "status": {
                            "currentPressure": 300,
                            "targetPressure": 300
                        }
                    },
                    "rearRight": {
                        "status": {
                            "currentPressure": 300,
                            "targetPressure": 300
                        }
                    }
                },
                "location": {
                    "coordinates": {
                        "latitude": ,
                        "longitude":
                    },
                    "address": {
                        "formatted": ""
                    },
                    "heading": 269
                },
                "currentMileage": 155275,
                "climateControlState": {
                    "activity": "INACTIVE"
                },
                "climateTimers": [
                    {
                        "isWeeklyTimer": false,
                        "timerAction": "DEACTIVATE",
                        "timerWeekDays": [],
                        "departureTime": {
                            "hour": 13,
                            "minute": 25
                        }
                    },
                    {
                        "isWeeklyTimer": true,
                        "timerAction": "DEACTIVATE",
                        "timerWeekDays": [
                            "MONDAY"
                        ],
                        "departureTime": {
                            "hour": 7,
                            "minute": 0
                        }
                    },
                    {
                        "isWeeklyTimer": true,
                        "timerAction": "DEACTIVATE",
                        "timerWeekDays": [
                            "MONDAY"
                        ],
                        "departureTime": {
                            "hour": 7,
                            "minute": 0
                        }
                    }
                ],
                "departurePlan": {},
                "requiredServices": [],
                "checkControlMessages": [
                    {
                        "type": "TIRE_PRESSURE",
                        "severity": "LOW"
                    },
                    {
                        "type": "ENGINE_OIL",
                        "severity": "LOW"
                    }
                ],
                "combustionFuelLevel": {
                    "remainingFuelPercent": 28,
                    "remainingFuelLiters": 16,
                    "range": 215
                },
                "driverPreferences": {
                    "lscPrivacyMode": "OFF"
                },
                "isDeepSleepModeActive": false,
                "securityOverviewMode": null,
                "vehicleSoftwareVersion": {
                    "puStep": {
                        "month": 7,
                        "year": 21
                    },
                    "iStep": {
                        "seriesCluster": "S15A",
                        "year": 21,
                        "month": 7,
                        "iStep": 550
                    }
                },
                "pwf": "STANDING_CUSTOMER_NOT_IN_VEH"
            },
            "charging_settings": null,
            "vin": "",
            "fetched_at": "2024-10-10T15:47:22.537953+00:00"
        },
        "fuel_and_battery": {
            "remaining_range_fuel": [
                215,
                "km"
            ],
            "remaining_range_electric": [
                null,
                null
            ],
            "remaining_range_total": [
                215,
                "km"
            ],
            "remaining_fuel": [
                16,
                "L"
            ],
            "remaining_fuel_percent": 28,
            "remaining_battery_percent": null,
            "charging_status": null,
            "charging_start_time": null,
            "charging_end_time": null,
            "is_charger_connected": false,
            "charging_target": null
        },
        "vehicle_location": {
            "location": {
                "latitude": ,
                "longitude":
            },
            "heading": 269,
            "vehicle_update_timestamp": "2024-10-10T15:47:22+00:00",
            "account_region": "row",
            "remote_service_position": null
        },
        "doors_and_windows": {
            "door_lock_state": "UNLOCKED",
            "lids": [
                {
                    "name": "leftFront",
                    "state": "CLOSED",
                    "is_closed": true
                },
                {
                    "name": "leftRear",
                    "state": "CLOSED",
                    "is_closed": true
                },
                {
                    "name": "rightFront",
                    "state": "CLOSED",
                    "is_closed": true
                },
                {
                    "name": "rightRear",
                    "state": "CLOSED",
                    "is_closed": true
                },
                {
                    "name": "hood",
                    "state": "CLOSED",
                    "is_closed": true
                },
                {
                    "name": "trunk",
                    "state": "CLOSED",
                    "is_closed": true
                },
                {
                    "name": "sunRoof",
                    "state": "CLOSED",
                    "is_closed": true
                }
            ],
            "windows": [
                {
                    "name": "leftFront",
                    "state": "CLOSED",
                    "is_closed": true
                },
                {
                    "name": "leftRear",
                    "state": "CLOSED",
                    "is_closed": true
                },
                {
                    "name": "rightFront",
                    "state": "CLOSED",
                    "is_closed": true
                },
                {
                    "name": "rightRear",
                    "state": "CLOSED",
                    "is_closed": true
                },
                {
                    "name": "rear",
                    "state": "CLOSED",
                    "is_closed": true
                }
            ],
            "all_lids_closed": true,
            "all_windows_closed": true,
            "open_lids": [],
            "open_windows": []
        },
        "condition_based_services": {
            "messages": [],
            "is_service_required": false
        },
        "headunit": {
            "idrive_version": "ID7",
            "headunit_type": "MGU",
            "software_version": "07/2021.50"
        },
        "check_control_messages": {
            "messages": [
                {
                    "description_short": "TIRE_PRESSURE",
                    "description_long": null,
                    "state": "LOW"
                },
                {
                    "description_short": "ENGINE_OIL",
                    "description_long": null,
                    "state": "LOW"
                }
            ],
            "has_check_control_messages": false
        },
        "climate": {
            "activity": "INACTIVE",
            "activity_end_time": null,
            "is_climate_on": false
        },
        "charging_profile": null,
        "tires": {
            "front_left": {
                "current_pressure": 290,
                "target_pressure": 300,
                "season": null,
                "manufacturing_week": null
            },
            "front_right": {
                "current_pressure": 300,
                "target_pressure": 300,
                "season": null,
                "manufacturing_week": null
            },
            "rear_left": {
                "current_pressure": 300,
                "target_pressure": 300,
                "season": null,
                "manufacturing_week": null
            },
            "rear_right": {
                "current_pressure": 300,
                "target_pressure": 300,
                "season": null,
                "manufacturing_week": null
            }
        },
        "available_attributes": [
            "gps_position",
            "vin",
            "remaining_range_total",
            "mileage",
            "remaining_fuel",
            "remaining_range_fuel",
            "remaining_fuel_percent",
            "condition_based_services",
            "check_control_messages",
            "door_lock_state",
            "timestamp",
            "lids",
            "windows"
        ],
        "brand": "bmw",
        "drive_train": "MILD_HYBRID",
        "drive_train_attributes": [
            "remaining_range_total",
            "mileage",
            "remaining_fuel",
            "remaining_range_fuel",
            "remaining_fuel_percent"
        ],
        "has_combustion_drivetrain": true,
        "has_electric_drivetrain": false,
        "is_charging_plan_supported": false,
        "is_charging_settings_supported": false,
        "is_lsc_enabled": true,
        "is_remote_charge_start_enabled": false,
        "is_remote_charge_stop_enabled": false,
        "is_remote_climate_start_enabled": true,
        "is_remote_climate_stop_enabled": true,
        "is_remote_horn_enabled": true,
        "is_remote_lights_enabled": true,
        "is_remote_lock_enabled": true,
        "is_remote_sendpoi_enabled": true,
        "is_remote_set_ac_limit_enabled": false,
        "is_remote_set_target_soc_enabled": false,
        "is_remote_unlock_enabled": true,
        "is_vehicle_active": false,
        "is_vehicle_tracking_enabled": true,
        "lsc_type": "ACTIVATED",
        "mileage": [
            155275,
            "km"
        ],
        "name": "530d xDrive",
        "timestamp": "2024-10-10T15:47:22+00:00",
        "vin": ""
    }
]

Ich dachte schlicht, dass es mit einer RegEx viel einfacher wäre.
Titel: Aw: Hilfe beim Escapen einer RegEx
Beitrag von: betateilchen am 10 Oktober 2024, 21:00:27
Warum nimmst Du nicht die erste Kilometerangabe, die in der dritten Zeile steht?

sub bmwTest {
my $input = 'Found 1 vehicles: 530d xDrive
VIN:
Mileage: 155275 km
Vehicle data:
[
    {
        "data": {'; # Rest habe ich absichtlich weggelassen

  $input =~ m/Mileage..(\d+)/;
  return $1;
}
Titel: Aw: Hilfe beim Escapen einer RegEx
Beitrag von: doc. am 10 Oktober 2024, 21:20:56
Ja, das hatte ich mir dann auch überlegt, ändert aber leider nix an meinem Problem...ich bekomme die selbe FM, die RegEx sähe ja auch fast identisch aus:

$outputBMW =~ /(/?/</=Mileage/:/ /)/\d/*;
Inzwischen habe ich mir das mit dem JSON angeschaut (hatte ich vorher noch nie gemacht), ich finde aber immer nur Beispiele wo nur ein Knoten "0" vorhanden war und darunter gleich die Daten. Wie müsste das denn bei meinem JSON aussehen? Mein Bemühen bis jetzt:

  my @outputBMW2 = split(/Vehicle data:/, $outputBMW);
  my $decoded = decode_json($outputBMW2[1]);
  my $mileage = $decoded->[0]->['mileage']->{0};

endet aber in einer FM:

2024.10.10 21:12:18 1: ERROR evaluating my $SELF=   $evalSpecials->{'%SELF'};{BMWauslesen()}: Not an ARRAY reference at ./FHEM/99_myUtils.pm line 26.

2024.10.10 21:12:18 3: BMWupdate: Not an ARRAY reference at ./FHEM/99_myUtils.pm line 26.
Titel: Aw: Hilfe beim Escapen einer RegEx
Beitrag von: betateilchen am 10 Oktober 2024, 21:22:42
Deine perl Syntax für die regex ist halt immer noch falsch.

Warum nimmst Du nicht die regex, die ich in meinem Test verwende? Die funktioniert ohne Fehlermeldung.

  $input =~ m/Mileage..(\d+)/;
Titel: Aw: Hilfe beim Escapen einer RegEx
Beitrag von: doc. am 10 Oktober 2024, 21:39:00
Ja, das funktioniert  :o  Aber ich müsste doch auch irgendwie mit dem RegEx Token (?<= arbeiten können...

Aber Du hast mir sowieso unglaublich geholfen, denn dank Dir hab ich mich (mit Unterstützung von ChatGPT) in das Thema JSON eingelesen und mit

my $mileage = $decoded->[0]->{'mileage'}->[0]
bekomme ich genau was ich brauche...und es wird mir die nächsten Schritte tausendmal einfacher machen...das mit den Arrays im JSON war etwas tricky.

Aber wirklich - TAUSEND DANK!
Titel: Aw: Hilfe beim Escapen einer RegEx
Beitrag von: doc. am 10 Oktober 2024, 21:40:14
Ach, sorry, das war Christoph und nicht Du  :)