user310291
user310291

Reputation: 38228

Javascript regex space or

I created this javascript regex

 (?<=\s|^|\.)[^ ]+\(

Here is my regex fiddle. The lines I am testing against are:

a bcde(
a bc.de(
bc(

See how these strings are matched: enter image description here

instead of matching on line 2

bc.de(

I wish to get only

.de(

Upvotes: 0

Views: 74

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627101

You can use

(?<=[\s.]|^)[^\s.]+\(

See the regex demo. If you do not want to match any whitespace, use a regular space:

(?<=[ .]|^)[^ .]+\(

Details:

  • (?<=[\s.]|^) - a positive lookbehind that requires a whitespace, start of string or a . to occur immediately to the left of the current location
  • [^\s.]+ - any one or more chars other than whitespace and a dot
  • \( - a ( char.

Note that is would be much better to use a consuming pattern here rather than rely on the lookbehind. You could match all till the first dot, or if there is no dot, match the first whitespace, or start of string, that are followed with any one or more chars other than space till a ( char. The point here is that you need to capture the part of the pattern you need to extract:

const regex = /(?:^[^.\r\n]*\.|\s|^)([^ (]+)\(/;
const texts = ["a bcde(", "a bc.de(", "bc("];
for (const text of texts) {
  console.log(text, '=>', text.match(regex)?.[1]);
}

Upvotes: 1

Related Questions