正则表达式:匹配短语中的所有单词
Regex: Matching all words in a phrase
这可能吗?
对于 hello how are you
这样的句子,我希望我的正则表达式为 return hello
how
are
you
。它只会 return 只是 hello
而不是其他词。
我的正则表达式:
[A-Za-z]*
非常感谢任何帮助。谢谢!
如果重要的话,我正在使用 Pharo Smalltalk。我也在 c# 测试过。
如果你只需要用空格分割句子,这可以使用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);
在这种情况下,您根本不需要正则表达式。只需使用 Split
.
string str = "hello how are you";
string[] parts = str.Split(' ');
如果您真的非常想要 Regex,\w+
因为 Regex 可以捕获任何单词。所以在 C# 中,正则表达式应该看起来像这样 string regex = "\w+"
如果你至少需要 word.
-
\w
代表任何包含字符的单词
+
量词代表至少一次
*
量词代表零次或多次
您可以在 Pharo 中找到有关 Regex 的章节:
我只想在空格上拆分字符串 运行:
Character space split: 'My String To split'
您将获得包含所有单词的 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)"
这可能吗?
对于 hello how are you
这样的句子,我希望我的正则表达式为 return hello
how
are
you
。它只会 return 只是 hello
而不是其他词。
我的正则表达式:
[A-Za-z]*
非常感谢任何帮助。谢谢! 如果重要的话,我正在使用 Pharo Smalltalk。我也在 c# 测试过。
如果你只需要用空格分割句子,这可以使用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);
在这种情况下,您根本不需要正则表达式。只需使用 Split
.
string str = "hello how are you";
string[] parts = str.Split(' ');
如果您真的非常想要 Regex,\w+
因为 Regex 可以捕获任何单词。所以在 C# 中,正则表达式应该看起来像这样 string regex = "\w+"
如果你至少需要 word.
-
\w
代表任何包含字符的单词 +
量词代表至少一次*
量词代表零次或多次
您可以在 Pharo 中找到有关 Regex 的章节:
我只想在空格上拆分字符串 运行:
Character space split: 'My String To split'
您将获得包含所有单词的 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)"