0

I have this regex1 :

(\w+)\n#(\w+)_(\w+)\n(\w+)

That captures the following text1 :

randomtext
#randomteeexxt_randomqlsdfjml
randomagain

But sometimes I have a fourth line in the text2 :

randomtext
#randomteeexxt_randomqlsdfjml
randomagain
stillrandom

So this following regex2 works :

(\w+)\n#(\w+)_(\w+)\n(\w+)\n(\w+)

The regex2 does not match anything of the text1, this is what I want.

The regex1 matches the 3 first lines of the text2, but I don't want it.

I want that the regex1 does not match anything of the text2.

G F
  • 321
  • 1
  • 5
  • 12

1 Answers1

2

You could try placing anchors around your current pattern to ensure that it applies to the entire input:

^(\w+)\n#(\w+)_(\w+)\n(\w+)$

Here is an example of how to use this pattern in JavaScript:

var str_pass = 'AAA\n#BBB_CCC\nDDD';
var str_fail = 'AAA\n#BBB_CCC\nDDD\nEEE';
console.log(/^\w+\n#\w+_\w+\n\w+$/.test(str_pass));
console.log(/^\w+\n#\w+_\w+\n\w+$/.test(str_fail));
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thanks for you answer. It does not work. It still captures the 3 first lines. I'm using https://regex101.com to test. – G F Oct 16 '19 at 13:37
  • @GF `It does not work` ... that totally depends on what your definition of the word `it` is. It doesn't work in the demo site, because that regex tool is designed to be applied as many times as possible. However, in most programming languages, the anchors I added would ensure that the _entire_ input matches the pattern. So, what tool/language are you actually using? – Tim Biegeleisen Oct 16 '19 at 13:40
  • Sorry for long answer, had to double check with my dev. We're using JavaScript, Node JS. Do you need more info ? – G F Oct 18 '19 at 07:38
  • Include your current JS code, and also state why my pattern is not working with it. – Tim Biegeleisen Oct 18 '19 at 07:41
  • const str = 'AAA\n#BBB_CCC\nDDD\nEEE'; const ret = str.match(/^\w+\n#\w+_\w+\n\w+$/m); console.log(ret); – G F Oct 18 '19 at 08:23
  • [ 'AAA\n#BBB_CCC\nDDD', index: 0, input: 'AAA\n#BBB_CCC\nDDD\nEEE', groups: undefined ] – G F Oct 18 '19 at 08:23
  • I'm waiting to have the Null result. Here it still takes the 3 first lines. – G F Oct 18 '19 at 08:24
  • 1
    @GF Check my updated answer, which now includes a JavaScript code sample. You should be using `test()` to check if an input string matches a regex pattern. – Tim Biegeleisen Oct 18 '19 at 09:01