我有一个相当大的字符串。在这个大字符串中,我想要获取所有以@@开头并以@@结尾的唯一单词。@@之间可以是文本、数字、字母数字或任何其他字符。
一旦我获取了所有以@@开头并以@@结尾的唯一单词,我想要使用与不同数组中的键匹配的值替换每个单词。
正在寻找C#的解决方案。
尝试这个正则表达式:
@@\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
包含匹配的值,比较每个值并根据您的标准进行替换。
\b
会导致模式在不想要的偏移处匹配。应该使用以下模式:*@@\b(?<word>.+?)\b@@* - User 12345678@@\b(.+?)\b@@
也不一定有效。它假设“单词”的第一个和最后一个字符将始终是单词字符(即匹配\w+
的字符)。从目前为止OP所说的内容来看,这似乎不是一个安全的假设。如果您知道第一个和最后一个字符始终是单词字符,则\b
是多余的。 - Alan Moore尝试以下代码(使用 Regex.Replace 方法):
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.
使用正则表达式和Linq的示例
string text = "@@bb@@@@cc@@@@sahasjah@@@@bb@@";
var matches = Regex.Matches(text, @"@@[^@]*@@");
var uniques = matches.Cast<Match>().Select(match => match.Value).ToList().Distinct();
Singleline
选项?你的正则表达式中没有点 (.
)。 - Alan MooreRegex regex = new Regex("@@(.*)@@");
或者,如果您不想使用正则表达式,请使用以下内容(我认为更容易理解)
var splittedString = yourString.Split(new string[] { "xx" }, StringSplitOptions.None);
试试这个,伙计……
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
}
}
我不会使用正则表达式来做这件事。这个方法更快:
//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(' ');
你可以使用正则表达式 @@.+?@@ 替换你的特殊字符串标记。
使用System.Text.RegularExpressions.Regex.Replace()查找和替换匹配的标记。
string.Split
,string.StartsWith
和string.Replace
这些同样好用的方法(对我来说更易读)。 - default