我在C#中创建了一个小解析器。
要解析的字符串是:
Hello [Name] [LastName] how are you? [FirstTime]this is your first time isnt it?[/FirstTime] Bye!
[Name]和[LastName]的我的C#代码是:
message = message
.Replace("[FirstName]", user.FirstName)
.Replace("[LastName]", user.LastName)
bool isFirstTime = user.FirstLogin;
我的问题出在[FirstTime] [/FirstTime]
之间。如果isFirstTime
为真,我想在标签之间保留字符串,如果它是假的,我想丢弃标签内的文本。
知道如何解决这个问题吗?
示例结果:
你好詹姆斯邦德你好吗?这是你第一次不是吗?再见!
编辑:我忘了说示例字符串只是一个示例,字符串是"用户定义"所以使用stringbuilder并不适用于我的情况。
答案 0 :(得分:1)
使用此正则表达式模式查找并替换FirstName块:
[[FirstTime]](.*)[[/FirstTime]]
然后您的代码可能是:
Regex rgx = new Regex("[[FirstTime]](.*)[[/FirstTime]]");
File.WriteAllText("", rgx.Replace("Hello [Name] [LastName] how are you? [FirstTime]this is your first time isnt it?[/FirstTime] Bye!", "Ali"));
答案 1 :(得分:1)
以下是您可能正在寻找的正则表达方式:
var FirstLogin = false;
var FirstName = "James";
var LastName = "Bond";
var message = "Hello [FirstName] [LastName] how are you? [FirstTime]this is your first time isnt it?[/FirstTime] Bye!";
message = message
.Replace("[FirstName]", FirstName)
.Replace("[LastName]", LastName);
var isFirstTime = FirstLogin;
if (FirstLogin)
message = Regex.Replace(message, @"\[/?FirstTime\]", string.Empty);
// Hello James Bond how are you? this is your first time isnt it? Bye!
else
message = Regex.Replace(message, @"\[FirstTime\].*?\[/FirstTime\]", string.Empty);
// Hello James Bond how are you? Bye!
REGEX EXPLANATION :
\[/?FirstTime\]
- 匹配[FirstTime]
或[/FirstTime]
字面意思\[FirstTime\].*?\[/FirstTime\]
- 匹配最近出现的[FirstTime]
和[/FirstTime]
之间的任何文本(不考虑嵌套的BBtags)。如果您有嵌套标记,则可以考虑使用2个正则表达式:
\[FirstTime\](?:(?!\[/?FirstTime\]).)*\[/FirstTime\]
上面的这一个将匹配最近的FirstTime
标记对。下面的那个可以匹配最远的那个:
\[FirstTime\](?:\[([^]]*)\].*?\[/\1\]|.*?)*\[/FirstTime\]
答案 2 :(得分:0)
您可以使用stringbuilder类:
StringBuilder builder = new StringBuilder();
builder.Append("Hello ");
//Name
builder.Append(Name);
builder.Append(" ");
builder.Append(LastName);
builder.Append(" How are you? ");
//First time
if(FirstTime){
builder.Append(" This is your first time isn't it? ");
}
//Bye
builder.Append(" Bye!");
//Convert to string
String sentence = builder.ToString();