Home > OS >  Regex get all numbers in a string into one group
Regex get all numbers in a string into one group

Time:05-30

I have a column defined as a string with numbers in it I want to extract just the numbers into one single group however, I am able to get only the groups of consecutive numbers by (\d )

e.g. sale34sfo56rce22 to be extracted to salesforce and 345622 But I get groups of 34 56 22

Pow21er56BI to be extracted to PowerBI and 2156

Na12me to be extracted to Name and 12

What should be the best way?

I am using Tableau hence, I cannot extract each group and concat them as Tableau just extracts the first group and not the next.

CodePudding user response:

You can use two variables in js to have it.

    var target = "12div3_id_12";
    var tar_str = target.replace(/[0-9.]/g, "");
    var tar_num = target.replace(/[^0-9.]/g, "");

    console.log(tar_str)
    console.log(tar_num)

CodePudding user response:

The best solution without joining an array to a string is @JvdV's suggestion.

import re

re.sub(r"[a-z]", "", "sale34sfo56rce22")  # 345622
re.sub(r"\d", "", "sale34sfo56rce22")     # salesforce

Or just you can filter chars from the string and join them together

"".join(filter(str.isdigit, "sale34sfo56rce22"))  # 345622
"".join(filter(str.isalpha, "sale34sfo56rce22"))  # salesforce
  • Related