【问题标题】:Regex: Matching all words in a phrase [duplicate]正则表达式:匹配短语中的所有单词[重复]
【发布时间】:2016-02-23 17:24:30
【问题描述】:

这可能吗?

对于像hello how are you 这样的句子,我希望我的正则表达式返回hello how are you。它只会返回 hello 而不是其他单词。

我的正则表达式:

[A-Za-z]*

非常感谢任何帮助。谢谢! 如果重要的话,我正在使用 Pharo Smalltalk。我也在 中测试过。

【问题讨论】:

    标签: c# c# regex string smalltalk pharo


    【解决方案1】:

    也在Pharo发送#substrings消息:

    'Hello how are you' substrings
    

    并获取数组:

    #('Hello' 'how' 'are' 'you').
    

    【讨论】:

      【解决方案2】:

      您可以在此处找到有关 Pharo 中正则表达式的章节:

      https://ci.inria.fr/pharo-contribution/view/Books/job/DeepIntoPharo/lastSuccessfulBuild/artifact/tmp/PBE2.pdf

      我只想在可以运行的空格上拆分字符串:

      Character space split: 'My String To split'

      你会得到一个包含所有单词的 OrderedCollection。

      【讨论】:

        【解决方案3】:

        如果您只需要用空格分隔句子,可以使用string.Split() 方法:

        var s = "hello how are you";
        var words = s.Split();
        

        如果要使用正则表达式:

        var s = "hello how are you";
        var regex = "\\w+";
        var words = Regex.Matches(s, regex).Cast<Match>().Select(m => m.Value);
        

        【讨论】:

        • 所以如果我理解正确,正则表达式引擎本身不能返回多个匹配项,所以这取决于您可以在编程语言中使用的类?
        • @KingDan:每种编程语言都定义了它的正则表达式语法(主要是 PCRE)。您可以使用的方式取决于为它实现的类/函数
        • 该死,所以我想我遇到了 Smalltalk 问题。我能够在 C# 中正常工作。感谢您的帮助!
        • 不,不是闲聊问题。你的正则表达式不匹配超过你好
        • @StephanEggermont:我的代码是用 C# 编写的,我刚刚跑了,给了我 4 个字。
        【解决方案4】:

        在这种情况下,您根本不需要 Regex。只需使用Split

        string str = "hello how are you";
        string[] parts = str.Split(' ');
        

        如果您真的非常想要正则表达式,\w+ 因为正则表达式可以捕获任何单词。因此,在 C# 中,如果您至少需要 word,正则表达式应该看起来像这样 string regex = "\\w+"

        • \w 代表任何单词,包括字符为
        • + 量词代表至少一次
        • * 量词代表零次或多次

        【讨论】:

          【解决方案5】:

          标准试图匹配,但它没有匹配,因为有空格

          matcher := RxMatcher forString: '[A-Za-z]*'.
          matcher matches: 'hello how are you'
          
          false
          

          如果您要求所有匹配项,它会告诉您有 5 个,因为 * 也匹配零个字符

          matcher := RxMatcher forString: '[A-Za-z]*'.
          matcher matchesIn: 'hello how are you'
          
          "an OrderedCollection('hello' 'how' 'are' 'you' '')"
          

          对于想要的结果,您可以尝试

          matcher := RxMatcher forString: '[A-Za-z]+'.
          matcher matchesIn: 'hello how are you'
          
          "an OrderedCollection('hello' 'how' 'are' 'you')"
          

          如果你想知道单词的长度是多少

          matcher := RxMatcher forString: '[A-Za-z]+'.
          matcher matchesIn: 'hello how are you' collect: [ :each | each size ]
          
          "an OrderedCollection(5 3 3 3)"    
          

          【讨论】:

            猜你喜欢
            • 2017-05-26
            • 1970-01-01
            • 1970-01-01
            • 2016-03-17
            • 1970-01-01
            • 2011-06-03
            • 1970-01-01
            • 2019-09-29
            • 1970-01-01
            相关资源
            最近更新 更多