0

I`m a beginner of Regex. When I was trying to select lines starting with a nondigit character in this test file,

1 2012-01-01 12:00:00
2 2013-01-01 13:00:00
3 2012asdas
4 asdasasad

I tried /^\D and got what I want:

1 2012-01-01 12:00:00
2 2013-01-01 13:00:00
3 2012asdas
4 **a**sdasasad

Then, I was curious about if I could do the same job with /^[^\d], but it just matched all the lines:

1 **2**012-01-01 12:00:00
2 **2**013-01-01 13:00:00
3 **2**012asdas
4 **a**sdasasad

I then tried /^[^\w] and got the same result. Thus, I`m thinking which part of the regex is wrong. The question might be trivial, but any feedback is appreciated.

Leon
  • 1
  • 1
  • you can have a look at this https://stackoverflow.com/questions/26350856/regex-to-match-all-words-not-starting-with-digit, i hope it answers your question – Prabhjot Kaur Oct 25 '19 at 06:34
  • Which language you're working with ? it does work [`^[^\d]`](https://regex101.com/r/xjU7VA/1/) – Code Maniac Oct 25 '19 at 06:42

1 Answers1

0

Here is an explanation:

  • \d matches 1 digit
  • \D matches anything that is not a digit
  • \d+ matches multiple digits
  • [\d] matches all the characters in brackets which are digits
  • [^\d] matches all the characters that are not in brackets, so no digits
  • [\D] products the same outcome as above
  • ^ matches the beginning of the line

so ^\D+ will match line starting with non digits

You should try this really powerful regex tester here: https://regex101.com/

antoni
  • 5,001
  • 1
  • 35
  • 44
  • Thx for the quick response! I just wonder why `/^[^\d]` doesn`t give the same result as `/^\D`? – Leon Oct 25 '19 at 06:38
  • it does: `/^[^\d]+/.test('fgdl324532')` returns true as well as `/^\D+/.test('fgdl324532')` (in javascript - you can test in console) – antoni Oct 25 '19 at 06:41
  • I tried on regex101.com, and it does have the same effect. But why it doesn`t in vim? – Leon Oct 25 '19 at 06:49
  • this is probably because of that: https://stackoverflow.com/questions/3604617/why-does-vim-have-its-own-regex-syntax – antoni Oct 25 '19 at 06:54