只有当它们不包含在子字符串中时才用正则表达式分隔空格(split spaces with a regex only if they are not contained in a substring)

编程入门 行业动态 更新时间:2024-10-28 06:34:33
只有当它们不包含在子字符串中时才用正则表达式分隔空格(split spaces with a regex only if they are not contained in a substring)

我应该用空格(或\ r \ n \ t)分割一个可能包含子串的字符串

例:

text 'contained in' a string

我试过像正则表达式:

/[?<!\"\'](\ )*[?!\"\']/g;

string.split(regex)应该返回:

["text", "'contained in'", "a", "string"]

但这是错的......我在很长时间内解决这个问题:@

现在,我创建了一个split函数,如果有超出子串的话,会自动用sepchar分割,但是我正在寻找一个带正则表达式的简单解决方案,如果可能的话,显然:P

I should split by spaces (or \r\n\t) a string that could contains substrings

Example:

text 'contained in' a string

I have tried with a regex like:

/[?<!\"\'](\ )*[?!\"\']/g;

string.split(regex) should returns:

["text", "'contained in'", "a", "string"]

.

But it's wrong... I'm freaking from much time to resolve it :@

For now, I made a split function that automatically split by a sepchar if there are out of substrings, but I'm looking for a simple solution with regex, if possible, obviously :P

最满意答案

你可以这样做:

(?:'(.*)'|(\b[\w]+\b))

工作正则表达式示例:

http://regex101.com/r/oJ2nQ9

或者甚至更好,而不是使用单词bounderies(因为你的字符串可能包含特殊字符)..这会更好:

(?:'(.*?)'|(?:[\s]*|^)([^\s]+)(?:[\s]*|$))

样本字符串:

text 'contained in' a string-with special's chars.

火柴:

"text", "contained in", "a", "string-with", "special's", "chars."

工作正则表达式示例:

http://regex101.com/r/iP3iJ1

You could do this:

(?:'(.*)'|(\b[\w]+\b))

Working regex example:

http://regex101.com/r/oJ2nQ9

Or even better, rather than using word bounderies (because your string may contain special characters).. This would be better:

(?:'(.*?)'|(?:[\s]*|^)([^\s]+)(?:[\s]*|$))

Sample string:

text 'contained in' a string-with special's chars.

Matches:

"text", "contained in", "a", "string-with", "special's", "chars."

Working regex example:

http://regex101.com/r/iP3iJ1

更多推荐

本文发布于:2023-07-31 15:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1344952.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:空格   字符串   中时   不包含   才用

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!