0

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.

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Massive thanks for your help, exactly what I want
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.