我会用正则表达式:
第一个例子,如果你只有Status: ZZZZZ
- 类似的消息:
String status = Regex.Match(@"(?<=Status: ).*");
// Explanation of "(?<=Status: ).*" :
// (?<= Start of the positive look-behind group: it means that the
// following text is required but won't appear in the returned string
// Status: The text defining the email string format
// ) End of the positive look-behind group
// .* Matches any character
第二个例子,如果你只有Status: ZZZZZ
和Action: ZZZZZ
- 类似的消息:
String status = Regex.Match(@"(?<=(Status|Action): ).*");
// We added (Status|Action) that allows the positive look-behind text to be
// either 'Status: ', or 'Action: '
现在,如果您想让用户有可能提供自己的格式,您可以想出类似的东西:
String userEntry = GetUserEntry(); // Get the text submitted by the user
String userFormatText = Regex.Escape(userEntry);
String status = Regex.Match(@"(?<=" + userFormatText + ").*");
这将允许用户提交其格式,如Status:
, or Action:
, or This is my friggin format, now please read the status -->
...
该Regex.Escape(userEntry)
部分对于确保用户不会通过提交特殊字符(如\
, ?
, *
... )来破坏您的正则表达式很重要
要知道用户是在格式文本之前还是之后提交状态值,您有几种解决方案:
您可以询问用户他的状态值在哪里,然后相应地构建您的正则表达式:
if (statusValueIsAfter) {
// Example: "Status: Closed"
regexPattern = @"(?<=Status: ).*";
} else {
// Example: "Closed:Status"
regexPattern = @".*(?=:Status)"; // We use here a positive look-AHEAD
}
或者您可以更聪明一些,并为用户条目引入一个标签系统。例如,用户提交Status: <value>
或<value>=The status
您通过替换标签字符串来构建正则表达式。