查找以@@开头的所有单词,并以长字符串中的@@结尾

时间:2013-07-30 07:00:59

标签: c# .net regex string

我有一个很大的字符串。在那个大字符串中,我希望以@@开头所有UNIQUE字,并以@@结尾。 @@之间可以是文本,数字或字母数字或任何内容。

一旦我得到所有以@@开头并以@@结尾的单词,我想用一个与不同数组中的键匹配的值替换每个单词。

在C#中寻找解决方案。

7 个答案:

答案 0 :(得分:4)

试试这个正则表达式:

@@\b\S+?\b@@

示例代码:

List<string> lst = new List<string>();
MatchCollection mcol = Regex.Matches(sampleString,@"@@\b\S+?\b@@");

foreach(Match m in mcol)
{
    lst.Add(m.Tostring());
}

此处lst包含匹配的值,比较每个值并根据您的条件替换它。

Sample live demo

答案 1 :(得分:1)

使用Regex和Linq的示例

string text = "@@bb@@@@cc@@@@sahasjah@@@@bb@@";
var matches = Regex.Matches(text, @"@@[^@]*@@");
var uniques = matches.Cast<Match>().Select(match => match.Value).ToList().Distinct();

答案 2 :(得分:1)

尝试以下代码(使用Regex.Replace Method):

string s = @"@@Welcome@@ to @@reg-ex@@ @@world@@.";
Dictionary<string, string> sub = new Dictionary<string,string>{
    { "@@reg-ex@@", "regular expression" },
    { "@@world@@", "hell" },
};
Regex re = new Regex(@"@@.*?@@");
Console.WriteLine(re.Replace(s, x => {
    string new_x;
    return sub.TryGetValue(x.ToString(), out new_x) ? new_x : x.ToString();
}));

打印:

@@Welcome@@ to regular expression hell.

答案 3 :(得分:0)

您可以执行以下操作

Regex regex = new Regex("@@(.*)@@");

或者,如果你不想要正则表达式使用以下(我认为更容易理解)

var splittedString = yourString.Split(new string[] { "xx" }, StringSplitOptions.None);

答案 4 :(得分:0)

您可以使用正则表达式@@。+?@@来替换您的特殊字符串标记。

使用System.Text.RegularExpressions.Regex.Replace()查找和替换匹配的令牌。

答案 5 :(得分:0)

试试这个伴侣.....

string yourString = ""; // Load your string
string[] splits = Regex.Split(yourString, "[ \n\t]"); //Split the long string by spaces, \t and \n
foreach (string str in splits)
{
    if(Regex.IsMatch(str, "^^@@.*?@@$$")) // Find words starting and ending with @@
    {
        // You may replace either splits values or build a new string according your specification
    }
}

答案 6 :(得分:0)

我不会使用正则表达式。这更快:

//Pseudo code
string[] parts = yourLongString.split("@@");
for(i=0;i<parts.length;i++){
    if(parts[i].indexOf(' ')<0){
        // there is no space, it is a keyword
        parts[i]=yourDictionary[parts[i]];
    }
}
yourFinalText=parts.join(' ');
相关问题