如何从特定单词开始获取子字符串 [英] How to get sub string starts from specific word

查看:108
本文介绍了如何从特定单词开始获取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我有这样的文字,例如:

这里有一种新的护理方式,

如何从中获取子字符串

例如,我希望从new到word的字符串什么都不会得到

这里没有新护理


谢谢大家:)

Hello all

I have a text like this for example:

there is a new care here, nothing else

how can I get a sub string from it

for example I want the string from word new to word nothing to get

new care here, nothing


thank you all : )

推荐答案

如果您确定确定要查找的起始词是"new",而结束词是"nothing",则可以搜索为您的字符串中的这些单词找到它们的索引.一旦有了索引,就可以使用它来做子字符串.

此处 [
希望对您有所帮助.
If you know for sure the the start word you are looking for is "new" and the end word is "nothing" you can search for these words in your string and find their index. Once you have the index, you can use that to do the substring.

Here[^] is an MSDN article that can explain it with a good example.

The problem you may encounter, is if there is more than one word "new" or "nothing" in your sentence.

Hope this helps.


Regex 类可用于从上述文本中检索所需的sub string.

如果需要only first出现子字符串,则可以按以下方式使用Regex Match 方法:
The Regex class can be used to retrieve the required sub string from the above text.

If only first occurrence of the sub string is required then the Match method of Regex can be used as follows:
string text = @"there is a new care here, nothing else";
Match match = Regex.Match(text,@"new.*?nothing",
    RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
if (match.Success)
	Console.WriteLine (match.Value);
//Output
//new care here, nothing


如果需要子字符串的multiple occurrences,则可以按如下方式使用Regex 类的Matches 方法:


If multiple occurrences of the sub string is required then the Matches method of Regex class can be used as follows:

string text2 = @"there is a new care here, nothing second new care here second time, nothing else";
MatchCollection matches = Regex.Matches(text2,@"new.*?nothing",
    RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
foreach (Match m in matches)
{
    Console.WriteLine (m.Value);
}
//Output
//new care here, nothing
//new care here second time, nothing


这篇关于如何从特定单词开始获取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆