简体   繁体   中英

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: 在此处输入图像描述

instead of matching on line 2

bc.de(

I wish to get only

.de(

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM