简体   繁体   English

Javascript 正则表达式空格或

[英]Javascript regex space or

I created this javascript regex我创建了这个 javascript 正则表达式

 (?<=\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而不是在第 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 . (?<=[\s.]|^) - 需要空格、字符串开头或. to occur immediately to the left of the current location立即出现在当前位置的左侧
  • [^\s.]+ - any one or more chars other than whitespace and a dot [^\s.]+ - 除空格和点之外的任何一个或多个字符
  • \( - a ( char. \( - 一个(字符。

Note that is would be much better to use a consuming pattern here rather than rely on the lookbehind.请注意,在这里使用消费模式会好得多,而不是依赖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:您可以匹配所有直到第一个点,或者如果没有点,则匹配第一个空格或字符串的开头,然后是除空格之外的任何一个或多个字符,直到 a (字符。这里的重点是您需要捕获您需要提取的模式部分:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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