1

I am new to regular expressions. While exploring it I found that result of the regular expression [.^;] and [;] are same and am trying to figure out an explanation. String is Hello;World As per my knowledge, ^ is for negation so shouldn't it skip the next character to it which is ';' in this case?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Tejas
  • 391
  • 2
  • 7
  • 19

3 Answers3

2

[.^;] doesn't do what you expect as ^ is treated as literal ^ only not negation.

To negate it use ^ at 1st position inside character class:

[^.;]
  • [.^;] becomes a character class that matches literals . OR ^ OR ;
  • [^.;] becomes a negation character class that matches anything but literals . OR ;
  • [;] is also a character class that matches literal ; only
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • appreciate the explanation @anubhava.. also I found this question helpful.. http://stackoverflow.com/questions/977251/regular-expressions-and-negating-a-whole-character-group – Tejas Sep 10 '14 at 08:46
1

^ only negates character groups if it is the first character in a group.

[.^;] will match any of the three characters in the group (a literal period, a caret or a semicolon). On the other hand, [^.;] will match anything not in the group (any letter, any digit, anything else but a literal period or semicolon).

knittl
  • 246,190
  • 53
  • 318
  • 364
0

They are not the same.

A carat ^ only means negation when it's the first character in a character class.

This regex [.^;] means "either a literal dot or a carat or a semi-colon"

This regex [;] means "a semi-colon".

Bohemian
  • 412,405
  • 93
  • 575
  • 722