0

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(
8
  • Do you mean [^ ] should not match dots? Then use (?<=\s|^|\.)[^\s.]+\( Commented Mar 20, 2021 at 23:02
  • Also, you may match until first . if present and simply capture the necessary string part with (?:^[^.\r\n]*\.|\s|^)(\S+)\( Commented Mar 20, 2021 at 23:03
  • how about adding the \. in the exclusion group ? [^\. ] ? Commented Mar 20, 2021 at 23:05
  • @WiktorStribiżew [^ ] should not match space. Commented Mar 20, 2021 at 23:06
  • [^ ] does not match space. What I asked was if you wanted this pattern to also stop matching dots, which you confirmed later. So my first comment regex also works. Commented Mar 20, 2021 at 23:20

1 Answer 1

1

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]);
}

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

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.