【问题标题】:Regex for comma separated string with/without spaces带/不带空格的逗号分隔字符串的正则表达式
【发布时间】:2018-04-05 13:59:10
【问题描述】:

我想创建一个正则表达式,我想在其中提取满足模式的字符串。

输入字符串有以下两种可能的出现方式

  1. type MyClass inherits SomeClass,SomeOtherClass implements Node
  2. type MyClass inherits SomeClass, SomeOtherClass implements Node

注意: 实现字可以是extend/union/intersection 等。

正则表达式应从上述输入字符串中提取"inherits SomeClass, SomeOtherClass" 字符串。

我尝试了多个 SO 答案和不同的在线资源,但都无法获得成功。我使用了/inherits\s(.*?)\s/mg,它只适用于第一种情况。

满足这两种情况的正则表达式是什么?帮助将不胜感激。

JSFiddle here

【问题讨论】:

标签: javascript regex regex-group


【解决方案1】:

你可以使用

/inherits\s+\w+(?:\s*,\s*\w+)*/g

请参阅regex demo

详情

  • inherits - 文字子串
  • \s+ - 1+ 个空格
  • \w+ - 1 个以上的字符(字母、数字或下划线)
  • (?:\s*,\s*\w+)* - 零次或多次 (*) 出现:
    • \s*,\s* - , 包含 0+ 个空白字符
    • \w+ - 1+ 个单词字符

JS 演示:

var regex = /inherits\s+\w+(?:\s*,\s*\w+)*/g;

var input1 = "type MyClass inherits SomeClass,SomeOtherClass implements Node";
var input2 = "type MyClass inherits SomeClass, SomeOtherClass implements Node";

var result1 = input1.match(regex);
var result2 = input2.match(regex);

document.write("result 1: "+ result1);
document.write("<br>")
document.write("\n result 2: "+ result2);

【讨论】:

  • 你拯救了我的一天!非常感谢!我会尽快接受答案:)
【解决方案2】:

检查字符串后面是否跟implements

var regex = /inherits\s+(.*)\s+(?=implements?)/mg;

var str1 = "type MyClass inherits SomeClass,SomeOtherClass implements Node";
var str2 = "type MyClass inherits SomeClass, SomeOtherClass implements Node";

str1.match( regex ) //["inherits SomeClass,SomeOtherClass "]

str2.match( regex ) //["inherits SomeClass, SomeOtherClass "]

【讨论】:

  • 非常感谢您,implements 字可以是任何东西。检查更新的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 2011-09-20
相关资源
最近更新 更多