Jan Paepke
Jan Paepke

Reputation: 2027

Javascript Regex matching strings separated by space but not containing a dot

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

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174874

Just get the matched characters by referring the group index 1.

(?:^| )([a-z]+(?= |$))

DEMO

> 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

Volune
Volune

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

hindmost
hindmost

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

Related Questions