0

I am trying figure out if it's possible to aggregate two patterns in a single one.

So my input could be something like this:

input = "200px"
input = "200pt"

My expected output would be result = ["200","pt"] or ["200","px"]

var result = input.match(/[^pt]+|pt/g)

Anyone knows if it's possible in a single pattern, handle pt or px suffixes ?

Solved

result = input.match(/^([0-9]+)(px|pt)$/).slice(1);

or

result = input.match(/^([0-9]+)((p[xt]|r?em)).slice(1); 

Thanks guys

0

2 Answers 2

3

You can use capturing groups:

input.match(/(\d+)(p[tx])/)
// -> Array ["200px", "200", "px"]

To get the exact result you wanted (without matching the whole string), you can split before the p:

input.split(/(?=p)/)
// -> Array ["200", "px"]
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the split technique which looks like the most efficient answer.
0

You can do it like this:

var input = "200px"; // or 200pt;
var result = input.match(/^([0-9]+)(px|pt)$/);
// result: ["200px", "200", "px"]
result = result.slice(1); // ["200", "px"]

The RegExp in English:

  • ^ start at the beginning of the string.
  • ([0-9]+) match 1 or more digits and capture them.
  • (px|pt) match px or pt and capture it.
  • $ end must be at the end of the string.

11 Comments

Instead of (px|pt) -which works of course-, you can use (p[xt]).
The first element is always the full match, you can't not have it. You can trim it off by: result.slice(1)
While it's not shorter, it's faster - it does not match p twice. Instead of (px|pt|em|rem) you'd rather write (p[xt]|r?em)
@Bergi's comment doesn't deserve a benchmark because you won't notice the difference in this case and you won't need one as the regex engine will first match p and won't need to save any states for backtracking then it will look for an t or x with no need for saving any states again.
@FritsvanCampen: As Sniffer explained, it doesn't need backtracking. Of course, a clever regex engine can optimise this, and the difference is hardly noticeable. And I agree, that readability here wins over regex design rules.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.