【问题标题】:Regular Expression to split a string with parentheses正则表达式用括号分割字符串
【发布时间】:2013-03-11 21:17:34
【问题描述】:

在 RegEx 方面需要帮助。使用 C#。

括号中的单词组(圆形或方框或卷曲)应视为一个单词。括号外的部分应根据空格“ ”进行拆分。

A) 测试用例 –

输入 - Andrew. (The Great Musician) John Smith-Lt.Gen3rd

结果(字符串数组)–
1. 安德鲁。
2. 伟大的音乐家
3. 约翰
4. Smith-Lt.Gen3rd

B) 测试用例——

输入 - Andrew. John

结果(字符串数组)–
1. 安德鲁。
2.约翰

C) 测试用例——

输入 - Andrew {The Great} Pirate

结果(字符串数组)–
1. 安德鲁
2. 伟大的
3.海盗

输入是一个人或任何其他实体的名称。当前系统是用 Access 编写的非常古老的系统。他们通过逐个字符扫描来做到这一点。我正在用 C# 替换它。

我想过分两步来做——首先是基于括号的拆分,然后是单词拆分。

我想把这些案例作为错误的输入丢弃 -

  1. 只有开始或结束括号可用

  2. 嵌套括号

总的来说,我只想拆分格式正确(如果有开始括号,则必须有结尾)输入。

【问题讨论】:

  • 由于括号可以嵌套,正则表达式是错误的工具。你必须编写一个解析器。
  • 这并不完全正确。根据输入,如果您知道相同类型的大括号不会被嵌套,那就没问题了。
  • "And {what (about strings} like) this?"
  • @JackManey 我敢打赌假设这些不会发生是安全的
  • @JackManey 基于示例输入,并基于我在括号中推断出的语义

标签: c# regex


【解决方案1】:

这是一个正则表达式,可以从您的示例中给出正确的结果:

\s(?=.*?(?:\(|\{|\[).*?(?:\]|\}|\)).*?)|(?<=(?:\(|\[|\{).*?(?:\}|\]|\)).*?)\s

这个正则表达式分为两部分,由|(OR) 语句分隔:

  1. \s(?=.*?(?:\(|\{|\[).*?(?:\]|\}|\)).*?) - 在 ()[]{} 的集合之前查找空格
  2. (?&lt;=(?:\(|\[|\{).*?(?:\}|\]|\)).*?)\s - 在 ()[]{} 的集合之后查找空格

以下是各部分的细分:

第 1 部分 (\s(?=.*?(?:\(|\{|\[).*?(?:\]|\}|\)).*?)):

1. \s             - matches white space
2. (?=            - Begins a lookahead assertion (What is included must exist after the \s
3. .*?            - Looks for any character any number of times. The `?` makes in ungreedy, so it will grab the least number it needs
4. (?:\(|\{|\[)   - A non passive group looking for `(`, `{`, or `[`
5. .*?            - Same as #3
6. (?:\]|\}|\))   - The reverse of #4
7. .*?            - Same as #3
8. )              - Closes the lookahead.  #3 through #7 are in the lookahead.

第 2 部分是相同的,但不是前瞻 ((?=)),而是后视 ((?&lt;=))

问题作者编辑后:

对于将搜索仅包含完整括号的行的正则表达式,您可以使用:

.*\(.*(?=.*?\).*?)|(?&lt;=.*?\(.*?).*\).*

您可以使用它将() 替换为{}[],这样您就有了完整的大括号和方括号。

【讨论】:

    【解决方案2】:

    这个怎么样:

    Regex regexObj = new Regex(
        @"(?<=\()       # Assert that the previous character is a (
        [^(){}[\]]+     # Match one or more non-paren/brace/bracket characters
        (?=\))          # Assert that the next character is a )
        |               # or
        (?<=\{)[^(){}[\]]+(?=\}) # Match {...}
        |               # or 
        (?<=\[)[^(){}[\]]+(?=\]) # Match [...]
        |               # or
        [^(){}[\]\s]+   # Match anything except whitespace or parens/braces/brackets", 
        RegexOptions.IgnorePatternWhitespace);
    

    这假定没有嵌套的括号/大括号/方括号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多