Reputation: 2027
I'm trying to match words that are not separated by dots in a string.
Because there are no lookbehinds in Javascript I've been struggling with this and can't get it to work.
Teststring 1: 'one two three.four five six.seven eight'
should match: 'one', 'two', 'five', 'eight'
Teststring 2: 'one.two three four.five six seven.eight'
should match: 'three', 'six'
Update:
Teststring 3: 'one.two three four five six seven.eight'
should match: 'three', 'four', 'five', 'six'
So far I have ( |^)(\w+)( |$)
, which kinda works on teststring 2, but fails to match 'two'
.
Is there any way I can do this with a regex, or should I split it into an array and then walk it?
Upvotes: 1
Views: 1221
Reputation: 174874
Just get the matched characters by referring the group index 1.
(?:^| )([a-z]+(?= |$))
> var re = /(?:^| )([a-z]+(?= |$))/g;
undefined
> var str = "one two three.four five six.seven eight";
undefined
> var matches = [];
undefined
> while (match = re.exec(str))
... matches.push(match[1]);
4
> console.log(matches);
[ 'one', 'two', 'five', 'eight' ]
Upvotes: 1
Reputation: 4339
With regex ( |^)\w+(?= |$)
'one two three.four five six.seven eight'.replace(/( |^)\w+(?= |$)/g, '$1TEST')
Or without regex (maybe more readable)
'one two three.four five six.seven eight'.split(' ').map(function(item) {
if(item.indexOf('.') < 0)
return 'TEST';
return item;
}).join(' ')
Upvotes: 3
Reputation: 7215
You don't need to use complex Regexp.
You can use splitting by space in conjunction with Array.filter()
method:
var result = str.split(' ').filter(function(item) {
return item.indexOf('.') < 0;
});
Upvotes: 0