Home > OS >  How to extract float and integer that end with specific characters using Regex
How to extract float and integer that end with specific characters using Regex

Time:11-10

I've the following XML (consider it as normal text) :

   <TextView
        android:layout_width="15dp"
        android:layout_height="match_parent"
        android:textSize="1.5sp" />

I'm using the following code to extract numbers, for example 15 and 1.5:

let largeOutputResult = inputXML.replace(/(\d )(sp|dp)/g, (_,num,end) => `${num*1.5}${end}`);

The issue I found is when I run the code, it extracts 15, 1 and 5, not 1.5, how I can fix that?

Thank you.

CodePudding user response:

Include the decimal point in your regex (and say all the digits before it are also optional):

const text = `\
<ImageView
    android:layout_width="15dp"
    android:layout_height="match_parent"
    android:layout_margin="1.5dp"
/>`;

const output = text.replace(/(\d*\.?\d )(sp|dp)/g, (_, num, end) => `${num * 1.5}${end}`);

console.log(output);

CodePudding user response:

You could also get a match only without groups.

\d*\.?\d (?=[sd]p\b)

Explanation

  • \d*\.?\d Match optional digits, optional dot and 1 digits (if you don't want to match only a leading dot only, then you can use \d (?:\.\d )?
  • (?= Positive lookahead
    • [sd]p\b Match either the words sp or dp to the right
  • ) close lookahead

Regex demo

const inputXML = `<ImageView
    android:layout_width="15dp"
    android:layout_height="match_parent"
    android:layout_margin="1.5dp"
/>`;
const largeOutputResult = inputXML.replace(/\d*\.?\d (?=[sd]p\b)/g, m => m * 1.5);
console.log(largeOutputResult);

  • Related