Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex two special characters in a row

Tags:

regex

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.

like image 515
James Avatar asked Jun 16 '13 22:06

James


People also ask

How do you handle special characters in regex?

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

What does \s mean in regex?

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]

What does * do in regex?

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.

How do you replace special characters in regex?

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]+", "")


1 Answers

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)`

like image 190
quetzalcoatl Avatar answered Sep 28 '22 05:09

quetzalcoatl