从字符串中检索子字符串 [英] Retrieving substring from a string

查看:109
本文介绍了从字符串中检索子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从一组字符串中检索药物的详细信息.

药物名称上附有公司名称,该名称是字符串.
ex-:BRUFEN [P&G].

我正在尝试检索公司名称.
基本上,公司名称位于方括号内,如示例所示.

我尝试使用内置的字符串函数,但无法从给定的字符串中检索公司名称.

任何帮助将不胜感激.

在此先谢谢您.

I am retrieving details of drugs from an Array of strings.

The drugs name have company name attached to it which is a string.
ex-:BRUFEN[P&G].

I am trying to retrieve the Company name.
Basically the company name lies within the square braces as shown in example.

I tried using builtin string functions but not able to retrieve the company name from the given string.

Any help would be appreciated.

Thanks in Advance.

推荐答案

如果您想使用RegEx,只需使用
If you want to use RegEx, simply go with
string output=
Regex.Match(myString,@"(?<=\[).*(?=\])").Value;


为什么不仅仅查看System.String的帮助页面?

平凡的方式是这样的:

Why not just looking at the help page for System.String?

The trivial way is this:

static string ExtractCompany(string source) {
   int bra = source.IndexOf('[');
   int ket = source.IndexOf(']');
   return source.Substring(bra, ket - bra - 1);
}



更复杂的方法是将正则表达式与模式"\ [.* \]"一起使用:



More sophisticated way would be using Regular Expression with the pattern "\[.*\]":

using Regex = System.Text.RegularExpressions.Regex;

//...

static string ExtractCompany(string source) {
    string pattern = @"\[.*\]";
    Regex regex = new Regex(pattern);
    var matches = regex.Matches(source);
    if (matches.Count < 1) return; //for example
    return matches[0].Value.Trim(new char[] { '[', ']' });
}



—SA



—SA


尝试关注
s.Substring(s.IndexOf("[") + 1, s.IndexOf("]") - s.IndexOf("[") - 1)


s是药物的名称.


where s is the drug''s name.


这篇关于从字符串中检索子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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