正则表达式从字符串中提取前 3 个单词 [英] Regex to extract first 3 words from a string
问题描述
我正在尝试替换字符串中除前 3 个单词以外的所有单词(使用 textpad).
I am trying to replace all the words except the first 3 words from the String (using textpad).
Ex 值:这是用于测试的字符串.
Ex value: This is the string for testing.
我只想提取 3 个单词:This is the
从上面的字符串中删除所有其他单词.
I want to extract just 3 words: This is the
from above string and remove all other words.
我找到了匹配 3 个单词的正则表达式 (\w+\s+){3}
但我需要匹配除前 3 个单词之外的所有其他单词和删除其他词.有人可以帮我吗?
I figured out the regex to match the 3 words (\w+\s+){3}
but I need to match all other words except the first 3 words and remove other words. Can someone help me with it?
推荐答案
具体如何取决于风味,但要消除除前三个词之外的所有内容,您可以使用:
Exactly how depends on the flavor, but to eliminate everything except the first three words, you can use:
^((?:\S+\s+){2}\S+).*
将前三个单词捕获到捕获组 1 中,以及字符串的其余部分.对于替换字符串,您使用对捕获组 1 的引用.在 C# 中,它可能如下所示:
which captures the first three words into capturing group 1, as well as the rest of the string. For your replace string, you use a reference to capturing group 1. In C# it might look like:
resultString = Regex.Replace(subjectString, @"^((?:\S+\s+){2}\S+).*", "${1}", RegexOptions.Multiline);
这篇关于正则表达式从字符串中提取前 3 个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!