正则表达式:匹配短语中的所有单词

时间:2016-02-23 17:24:30

标签: c# regex string smalltalk pharo

这可能吗?

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

My Regex:

[A-Za-z]*

非常感谢任何帮助。谢谢! 如果重要,我会使用Pharo Smalltalk。我也在进行了测试。

5 个答案:

答案 0 :(得分:6)

同样在Pharo中发送public class Base { public int BaseField; /// <summary> /// Apply the state of the passed object to this object. /// </summary> public virtual void ApplyState(Base obj) { BaseField = obj.BaseField; } } public class Derived : Base { public int DerivedField; public override void ApplyState(Base obj) { var src = srcObj as Derived; if (src != null) { DerivedField = src.DerivedField; } base.ApplyState(srcObj); } } 消息:

#substrings

并获取数组:

'Hello how are you' substrings

答案 1 :(得分:5)

您可以在此处找到有关Pharo中Regex的章节:

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

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

Character space split: 'My String To split'

您将获得包含所有单词的OrderedCollection。

答案 2 :(得分:4)

如果您只需要用空格分割句子,可以使用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);

答案 3 :(得分:2)

在这种情况下你根本不需要正则表达式。只需使用Split

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

如果你真的非常想要Regex,\w+正如Regex捕获任何单词一样。所以在C#中,如果你至少需要单词,那么正则表达式看起来应该是string regex = "\\w+"

  • \w代表包括字符
  • 在内的任何字词
  • +量词代表至少一次
  • *量词代表零次或多次

答案 4 :(得分:2)

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

,它没有
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)"