2

假设我得到了以下匹配:

将“hello world”插入{这是一个测试}

我想匹配空格并将每个匹配项推送到我的字符串数组,因为我需要知道字符串中文本的索引。

棘手的部分来了;必须排除单引号 (') 和大括号 ({}) 内的空格

我想要的结果是:

  1. 插入
  2. '你好世界'
  3. 进入
  4. {这是一个测验}

到目前为止,我已经能够排除单引号内的空格,但是我不知道如何将它与大括号结合起来。

我现在的正则表达式:

\s(?=(?:[^']|'[^'] ') $)

4

2 回答 2

2

这个很棘手。这次我考虑过匹配而不是拆分:

'[^']*'|\{[^\}]*\}|\S+

让我们稍微解释一下:

'[^']*'     # match a quoted string
|           # or
\{[^\}]*\}  # match zero or more characters between curly brackets
|           # or
\S+         # match a non-white space character one or more times

Online demo

于 2013-11-14T12:25:09.887 回答
1

Niekert, resurrecting this question because it had a simple solution that wasn't mentioned. This situation sounds very similar to Match (or replace) a pattern except in situations s1, s2, s3 etc.

Here's our simple regex:

{[^}]+}|( )

The left side of the alternation matches complete { ... } braces. We will ignore these matches. The right side matches and captures spaces to Group 1, and we know they are the right spaces because they were not matched by the expression on the left.

This program shows how to use the regex (see the results in the pane of the online demo):

<script>
var subject = "insert 'hello world' into {This is a test}";
var regex = /{[^}]+}|( )/g;
var match = regex.exec(subject);
replaced = subject.replace(regex, function(m, group1) {
    if (group1 == "" ) return m;
    else return "SplitHere";
});
splits = replaced.split("SplitHere");
document.write("*** Splits ***<br>");
for (key in splits) document.write(splits[key],"<br>");
</script>

Reference

How to match (or replace) a pattern except in situations s1, s2, s3...

于 2014-06-03T02:08:01.810 回答