Reputation: 1916
I am trying to create a Regex pattern in C# to find in a string, any [anything] that is not preceeded or followed by a "."... here is the pattern i have so far, which brings me to the actual problem: it only works on text that is NOT on the very first line??
Pattern:
([^\.]\[[^\[]*][^\.])
Consider the following "text" value:
[F] (never matches even if it should)
[F].[1234] (not a match, correct)
[P] (is a match)
If someone could help me with this, i would really appreciate it because i cannot, for the life of me, figure out why the very first line is not considered.
Thanks!
Upvotes: 1
Views: 70
Reputation: 4606
you can also use this pattern:
((^|[^\.])\[[^\[]*][^\.])
difference against yours is that [
could be just the first symbol in the line.
also i suggest you to use a site like http://regex101.com/ to better understand how regex works.
Upvotes: 0
Reputation: 24078
Your regex as you wrote it validates that the first [
must have a character that is not .
in front of it. The first [
is not preceded by any character so it fails.
With negative assertions you can say "match if there is no .
".
((?<!\.)\[[^\[]*](?!\.))
NODE EXPLANATION
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
(?<! look behind to see if there is not:
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
\[ '['
--------------------------------------------------------------------------------
[^\[]* any character except: '\[' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
] ']'
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
) end of \1
Upvotes: 4