[英]Regex for comma separated string with/without spaces
I want to create a Regex where I want to extract string that is satisfying pattern. 我想创建一个正则表达式,我要在其中提取令人满意的模式的字符串。
Input string can appear in below two possible ways 输入字符串可以以下两种方式出现
type MyClass inherits SomeClass,SomeOtherClass implements Node
type MyClass inherits SomeClass, SomeOtherClass implements Node
Note: implements word can be anything like
extend
/union
/intersection
etc. 注意:工具词可以是extend
/union
/intersection
等。
The regex should extract "inherits SomeClass, SomeOtherClass"
string from the above input string. 正则表达式应该从上面的输入字符串中提取"inherits SomeClass, SomeOtherClass"
字符串。
I tried multiple SO answers and different online sources, but can't get success in the same. 我尝试了多个SO答案和不同的在线资源,但无法同时获得成功。 I used /inherits\\s(.*?)\\s/mg
which only works for 1st case. 我用/inherits\\s(.*?)\\s/mg
仅适用于第一种情况。
What would be regex to satisfy both the cases? 满足这两种情况的正则表达式将是什么? Help would be appreciate. 帮助将不胜感激。
Check if the string is followed by implements
检查字符串后是否带有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 "]
You may use 您可以使用
/inherits\s+\w+(?:\s*,\s*\w+)*/g
See the regex demo . 参见regex演示 。
Details 细节
inherits
- a literal substring inherits
-文字子串 \\s+
- 1+ whitespaces \\s+
-1+空格 \\w+
- 1+ word chars (letters,digits or underscores) \\w+
-1个以上的字符字符(字母,数字或下划线) (?:\\s*,\\s*\\w+)*
- zero or more ( *
) occurrences of: (?:\\s*,\\s*\\w+)*
-零次或多次( *
)出现:
\\s*,\\s*
- a ,
enclosed with 0+ whitespace chars \\s*,\\s*
-a ,
用0+空格字符包围 \\w+
- 1+ word chars \\w+
-1个以上的字符字符 JS demo: 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.