简体   繁体   English

正则表达式匹配的字符串

[英]RegEx match of a string

Im working and a fun project with c# and now I have a problem with my RegEx . 我在用c#工作并且是一个有趣的项目,现在我的RegEx遇到了问题。 I have tried some varitations but didnt found a solution for this. 我尝试了一些变更,但没有找到解决方案。 I want a RegEx for this string "##Test1##" . 我想要此字符串"##Test1##"RegEx

So I have tried this RegEx here: 所以我在这里尝试过此RegEx:

[\#]{2}[a-zA-Z0-9]{1,}[\#]{2}

And its working fine but my problem is that, 其工作正常,但我的问题是,
When passed "###Test1###" the RegEx ignores the first and last # and matches on the inner "##Test1##" . 当传递"###Test1###" ,RegEx会忽略第一个和最后一个#并匹配内部的"##Test1##"

But I dont want that. 但是我不想要那个。

The RegEx only should match to this string ##Test1## . RegEx仅应与此字符串##Test1##匹配。

Hopefully here are some guys who can help me with that problem. 希望这里有些人可以帮助我解决这个问题。
Greetings, 问候,

If the regular expression should only match the string you've specified, here's your regular expression: 如果正则表达式应与您指定的字符串匹配,则为正则表达式:

^##Test1##$

If you want it to match a string like "##(any digit or letter here)##" , then this will work: 如果您希望它匹配"##(any digit or letter here)##"类的字符串,则可以使用:

^##[a-zA-Z0-9]+##$

This will match strings like 这将匹配字符串

##abc##
##123##

but not 但不是

###xxx###     <-- 3 #'s

I think the main part you're looking for here are these two symbols: 我认为您要在此处查找的主要部分是以下两个符号:

+------------------- matches the beginning of the string
|                +-- matches the end of the string
v                v
^##[a-zA-Z0-9]+##$

These two will make sure you're not searching to the string to see if your pattern exists inside it, but you're instead checking if the string matches the pattern completely. 这两项将确保你没有搜索到的字符串,看看你的格局里面它的存在,但如果字符串的模式匹配完全你不是检查。

This will match the required string when standing alone, and also if it is embedded in a longer character sequence: 单独使用时,以及嵌入较长的字符序列时,这将匹配所需的字符串:

[^#]*##[a-zA-Z0-9]+##[^#]*

Hello##World##! -> matches=true
##World##       -> matches=true

Hello##World### -> matches=false
###World###     -> matches=false

Well, thats because is contained inside, so is obviously right. 好吧,那是因为包含在里面,所以显然是正确的。 What about with "excluding" characters like at the end/beginning .^#* but obviosly that only works if you want to avoid just that character... 如果在结尾处使用“排除”字符(如.^#* ,那该怎么办,但显然只有当您要避免使用该字符时,该方法才有效...

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

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