0

Im working and a fun project with c# and now I have a problem with my RegEx. I have tried some varitations but didnt found a solution for this. I want a RegEx for this string "##Test1##".

So I have tried this RegEx here:

[\#]{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##".

But I dont want that.

The RegEx only should match to this string ##Test1##.

Hopefully here are some guys who can help me with that problem.
Greetings,

2
  • If you want a regex for that string, it would be "^##Test1##$". Can you tell us which bits will vary if you need to support different strings? ie. give us some examples? Commented Jul 31, 2014 at 13:11
  • I think the main point is that you need to apply anchors to ensure the string consists of only that Commented Jul 31, 2014 at 13:15

3 Answers 3

6

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:

^##[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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah thanks, ^ define the start of the match and $ the end, or? Thanks for that answer it works nice :)
0

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...

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.