tobiasrichter
tobiasrichter

Reputation: 23

RegEx matching space not starting/ending with char

I need to split the text to the words but I also need to ignore the & character. That means for example the word "h & m" has stay together. Regex must also work in JavaScript and node.js.

I used /(?!&)\s(?!&)/g. But that ignore space with & character only at end.

Upvotes: 2

Views: 42

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627292

If you cannot split (and you cannot split since there is no look-behind in JS), you need to match:

\S+(?:\s&\s\S+)*

See demo

Code:

var re = /(\S+(?:\s&\s\S+)*)/g; 
var str = 'H & M shopping mall';
var m = str.match(re);
document.getElementById("res").innerHTML = m;
<div id="res"/>

Upvotes: 1

karthik manchala
karthik manchala

Reputation: 13640

You can use look ahead and look behind... (just add < to your current regex)

/(?<!&)\s(?!&)/g
   ^

See DEMO

Explanation:

  • All spaces whose previous character is not &.. (?<!&) and next character is also not &.. (?!&)

Upvotes: 2

Related Questions