简体   繁体   English

C# - 使用正则表达式比较字符串的直接答案?

[英]C# - Straight-up answer for using Regex to compare strings?

I cannot understand the syntax at all!我完全看不懂语法! I feel like the stackoverflow community should get a simple solution to the problem I have (hopefully I'm not blind and have missed one of the thousands of regex questions here):我觉得 stackoverflow 社区应该得到一个简单的解决方案来解决我遇到的问题(希望我不是盲目的并且错过了这里成千上万的正则表达式问题之一):

string myString = "$randomText$";
string myString2 = "$otherStuff$";

What would I use to check if any string has "$*$"?我会用什么来检查任何字符串是否有“$*$”? So as long as there's 2 $'s on the outside of the text?所以只要文本外面有2个$?

Again, I'm sorry, and I Do understand there's other regex answers out there, but there's no way I'll ever understand it.再次,我很抱歉,我知道还有其他正则表达式的答案,但我不可能理解它。 I apologize, and have a good day.我道歉,祝你有美好的一天。

You can do this by using this:你可以通过使用这个来做到这一点:

string myString = "$randomText$";
var match = Regex.Match(myString , @"\$.+\$");

You have two options.你有两个选择。 Use regex or don't.是否使用正则表达式。 You could either substr the input string and check the first and last char are the $ sign, or you could use regex.您可以 substr 输入字符串并检查第一个和最后一个字符是$符号,或者您可以使用正则表达式。 If you're new and don't understand regex (learn to love it, a little goes a long way) then go with the substring checks.如果您是新手并且不了解正则表达式(学会喜欢它,有一点很长的路要走),然后进行子字符串检查。 You may also find that substringing is slightly faster than regex.您可能还会发现子串比正则表达式略快。

For those that want spoonfeeding (untested code).对于那些想要用勺子喂食的人(未经测试的代码)。 This will be (most likely) be faster than any regex check:这将(很可能)比任何正则表达式检查都快:

public bool DollahCheck(string inp, string stringToCheck = "$")
{
    return inp.Substring(0,1) == stringToCheck && inp.Substring(inp.Length - 1) == stringToCheck;
}

use this用这个
bool matched = Regex.Match(myString , @"yourRegexPattern").Success bool 匹配 = Regex.Match(myString , @"yourRegexPattern").Success

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM