0

I have two possible strings that I need to match:

+/-90000

and

+9000 / -80000

I need to recognise the two patterns separately so wrote some regex for this. The first single number string I can match like so:

/\+\/\-{1}/g

And i wrote this for the second:

/(\+(?=[0-9]+){1}|\-(?=[0-9]+){1}|\/(?=\s){1})/g

The second would also partially match the first the first number i.e. the -90000. Is there a way that they can be improved so that they match exclusively?

1
  • I am trying to match to determine which type of string the user has input into the system. They are allowed to input either into the same control but I need to perform different validation and work flows for each. Commented Oct 26, 2015 at 5:57

2 Answers 2

1

You can use a single expression:

^(?:(\+\/-\s*\d+)|((\+\s*\d+)\s*\/\s*(-\s*\d+)))$

The only restriction you'll have to work with would be that in the second type of input, the positive number should come first.

You'll get the matched group in matches[1] if the input was of type 1, and in matches[2] if it was of type 2. For the type-2 input, further matches of each number gets stored in matches[3] and matches[4].

You can see the demo on regex101.

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

Comments

1

Here are two solutions with slightly different semantics.

With the first, if the string is type 1 the number will be in capture group 1 (result[1]) and if it's type 2 the numbers will be in capture groups 2 and 3 (and capture group 1 will be null). The test for type 1, then, is result[1] !== null.

var a = '+/-90000';
var b = '+9000 / -80000';
var result;

var expr1 = /\+(?:\/-(\d+)|(\d+) \/ -(\d+))/;
result = a.match(expr1);
// => [ '+/-90000', '90000', null, null ]
result = b.match(expr1);
// => [ '+9000 / -80000', null, '9000', '80000' ]

With the second, if the string is type 1 the number will be in capture group 1 (and capture group 2 will be null), and if it's type 2 the numbers will be in capture groups 2 and 3. The test for type 1 is result[1] === null.

var expr2 = /\+(\d+ )?\/ ?-(\d+)/;
result = a.match(expr2);
// => [ '+/-90000', null, '90000' ]
result = b.match(expr2);
// => [ '+9000 / -80000', '9000', '80000' ]

Comments

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.