C# 正则表达式:匹配短语中的所有单词
这可能吗 对于像C# 正则表达式:匹配短语中的所有单词,c#,regex,string,smalltalk,pharo,C#,Regex,String,Smalltalk,Pharo,这可能吗 对于像你好这样的句子,我希望我的正则表达式返回你好你好你好你是谁。它只返回hello,而不返回其他单词 我的正则表达式: [A-Za-z]* 非常感谢您的帮助。谢谢 如果重要的话,我用的是Pharo Smalltalk。我也一直在测试。如果只需要将句子按空格分割,可以使用string.split()方法完成: var s = "hello how are you"; var words = s.Split(); 如果要使用正则表达式,请执行以下操作: var s = "hello
你好
这样的句子,我希望我的正则表达式返回你好
你好
你好
你是谁。它只返回hello
,而不返回其他单词
我的正则表达式:
[A-Za-z]*
非常感谢您的帮助。谢谢
如果重要的话,我用的是Pharo Smalltalk。我也一直在测试。如果只需要将句子按空格分割,可以使用
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);
var s=“你好”;
var regex=“\\w+”;
var words=Regex.Matches(s,Regex.Cast().Select(m=>m.Value);
在这种情况下,您根本不需要正则表达式。只需使用Split
string str = "hello how are you";
string[] parts = str.Split(' ');
如果您真的太想要正则表达式了,\w+
,因为正则表达式可以捕获任何单词。因此,在C#中,如果您至少需要word,正则表达式应该如下所示string Regex=“\\w+”
\w
代表包括以下字符在内的任何单词:
+
量词至少代表一次
*
量词表示零次或多次
您可以在Pharo中找到关于Regex的章节:
I您只想在可以运行的空间上拆分字符串:
字符空间拆分:“要拆分的我的字符串”
您将获得一个包含所有单词的OrderedCollection。同时在Pharo中发送#substrings
消息:
'Hello how are you' substrings
并获取阵列:
#('Hello' 'how' 'are' 'you').
标准会尝试匹配,但它不会匹配,因为存在空格
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)"
因此,如果我理解正确,正则表达式引擎本身无法返回多个匹配项,因此它取决于您在编程语言中可以使用的类?@KingDan:每种编程语言都定义其正则表达式语法(主要是PCRE)。您可以使用的方式取决于为它实现的类/函数Damn,因此我认为我遇到了Smalltalk问题。我可以在C#中正常工作。谢谢你的帮助!不,不是闲聊的问题。你的正则表达式不匹配超过hello@StephanEggermont:我的代码是C#,我只是跑过去给我4个单词。