0

I'm strugglig with regex. I need to find regex for pregmatch. If the string contains "\n" and not "\c\n", do something.

I do have a sentence "Thank you for tuning in to I-See News.\c\nJames Movesworth reporting.Today, let’s learn about\nQuick Attack." I tried something, but it's not working at all.

preg_match('/(?!\\c)(\\n)/', $string);

Thank you!

edit: My previous topic was closed, because it's simmilar to (Regular expression for a string containing one word but not another). Perhaps it is, but still if I modify my pattern according to the suggested topic,

^(?!.*\\c).*(\\n).*$

it still doesn't correctly display the answer. (In this case it displays "false" - but it shoud be true, before "Quick Attack" in the sentence is "\n".

chudst
  • 139
  • 3
  • 12
  • 3
    I think you want to use a lookbehind `(?<!\\c)\\n` https://regex101.com/r/GFuhbf/1 Your pattern uses a negative lookahead, which in this case will match all `\n` because the assertion right before it `(?!\\c)` is always going to be true when `\n` is directly following. The pattern `^(?!.*\\c)` will assert no occurrence in the whole line of `\c` – The fourth bird Jun 04 '22 at 13:16
  • 1
    That is due to backslash. To match a backslash, you need 4 backslashes. – Wiktor Stribiżew Jun 04 '22 at 13:21
  • 1
    [Or three](https://tio.run/##K8go@P/fxj7AI4CLKzU5I19BXV/DXjEmJiZZUwNI5mnqq1v//w8A) when using single quotes for the pattern... – bobble bubble Jun 04 '22 at 13:25
  • @chudst: If you get your question closed, my tip is the following: Edit the closed question (you can still edit it) and then ping in the comments and explain that you have improved it. That's far better than reproducing the topic once more (and it improves your original question). – hakre Jun 04 '22 at 13:27
  • 2
    Thanks to all of you! It's working with 3 backshlashes and with the pattern from The fourth bird. Hakre - thanks as well for the tip! – chudst Jun 04 '22 at 13:29
  • So, you want to remove the newline chars that are not immediately preceded with ``\c`` text? ``preg_replace('~(?<!\\\\c)\\n~u', "", $string)``? https://ideone.com/MgavE3? – Wiktor Stribiżew Jun 04 '22 at 13:32

1 Answers1

2

Thanks to The four bird, Wiktor, bobble bubble, this works:

preg_match('/(?<!\\\c)\\\n/', $string);
chudst
  • 139
  • 3
  • 12