I have this regex
\[.+\]\(.+\)
Why does it match this string entirely?
[test1](test1) thisbitshouldnotmatch [test2](test2)
It should only match [test1](test1)
and [test2](test2)
. thisbitshouldnotmatch
should not match.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
The regular expression \s is a predefined character class. It indicates a single whitespace character. Let's review the set of whitespace characters: [ \t\n\x0B\f\r]
The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern. `*' represents this operator. For example, `o*' matches any string made up of zero or more `o' s.
If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")
That is because the +
operator is greedy.
For expression \[.+\]\(.+\)
the characters are matched as follows:
[test1](test1) thisbitshouldnotmatch [test2](test2)
[..........................................](.....)
so, whole input matches!
You'd need to either use nongreedy:
\[.+?\]\(.+?\)
Or, explicitery disallow some characters
\[[^\]]+\]\([^)]+\)
(notice how I replaced the catch-any .
with a character group that excludes ]
or )
respectively)`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With