Save code snipped #6

Open
opened 2024-09-10 11:17:07 -03:00 by anavarro · 0 comments
Member

How to extract a value from a key= value pair in a string via regex

JS:

  // Extract the data from in the form of "key=value" string, position is in case the value has more than one "="
  private getDataFromString(str: string, search: string = '', position = 0) {
    const regex = new RegExp(`${search}\\s*=\\s*([^,\n]+)`);
    const match = str.match(regex);

    if (match === null) return '';

    const split = match.at(1)?.split('=');

    return split[position].trim();
  }

PHP

    private function find_in_str($key, $text)
    {
        $delimiters = ",\n;";
        $results = [];

        $regex = "/$key\s*=\s*([^$delimiters]+)/";
        $match = preg_match($regex, $text, $results);

        if (! $match) {
            return '';
        }

        return trim($results[1]);
    }
# How to extract a value from a key= value pair in a string via regex JS: ```js // Extract the data from in the form of "key=value" string, position is in case the value has more than one "=" private getDataFromString(str: string, search: string = '', position = 0) { const regex = new RegExp(`${search}\\s*=\\s*([^,\n]+)`); const match = str.match(regex); if (match === null) return ''; const split = match.at(1)?.split('='); return split[position].trim(); } ``` PHP ```php private function find_in_str($key, $text) { $delimiters = ",\n;"; $results = []; $regex = "/$key\s*=\s*([^$delimiters]+)/"; $match = preg_match($regex, $text, $results); if (! $match) { return ''; } return trim($results[1]); } ```
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference: alecodes/void#6
No description provided.