2

Javascript lets you split a string according to regular expression. Is it possible to use this functionality to split a string only when the delimiter is flanked by certain characters?

For example, if I want to split the string 12-93 but not at-13 using the - character? Is that possible?

Using a regular expression seems promising, but doing "12-93".split(/[0-9]-[0-9]/) yields ["1", "3"] because the flanking digits are considered to be part of the delimiter.

Can I specify the above split pattern (a dash preceded and followed by a digit) without chopping the flanking digits?

Other Examples

"55,966,575-165,162,787" should yield ["55,966,575", "165,162,787"]

"55,966,575x-165,162,787" should yield ["55,966,575x-165,162,787"]

"sdf55,966,575-165,162,787" should yield ["sdf55,966,575", "165,162,787"]

1
  • What about this: /d{2}-d{2}/ which specifies two digits a dash and two digits? Commented Nov 3, 2016 at 19:10

2 Answers 2

1

Using two adjacent character sets seems to work.

See example at https://regex101.com/r/uFHMW1/1

([0-9,a-z]+?[0-9]+)-([0-9]+[0-9,a-z]+)

Try this (live here https://repl.it/EOOQ/0 ):

var strings = [
"55,966,575-165,162,787",
"55,966,575x-165,162,787",
"sdf55,966,575-165,162,787",
];

var pattern = '^([0-9,a-z]+?[0-9]+)-([0-9]+[0-9,a-z]+)$';
var regex = new RegExp(pattern, 'i');

var matched = strings.map(function (string) {
	var matches = string.match( regex );
	if (matches) {
		return [matches[1], matches[2]];
	} else {
		return [string];
	}
});

console.log(matched)

You can also run the above expression as split() like:

string.split(re).filter( str => str.length )

where Array.filter() is used to get rid of the leading and trailing empty strings created when the RegExp matches your input.

var strings = [
"55,966,575-165,162,787",
"55,966,575x-165,162,787",
"sdf55,966,575-165,162,787",
];
var pattern = '^([0-9,a-z]+?[0-9]+)-([0-9]+[0-9,a-z]+)$';
var regex = new RegExp(pattern, 'i');

var matched = strings.map( string => string.split(regex).filter( str => str.length ) );

console.log(matched)

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

Comments

0

Try using a non-capturing lookahead. You are using a regex that captures all of the characters found, then uses that result as the split character(s).

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.