# \[help\] Regex pattern and raw strings

**URL:** <https://discuss.ocaml.org/t/help-regex-pattern-and-raw-strings/11747>\
**Category:** Learning\
**Tags:** string, pattern, str, regexp\
**Created:** [March 22, 2023, 12:33pm UTC](https://discuss.ocaml.org/t/help-regex-pattern-and-raw-strings/11747 "2023-03-22T12:33:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![anzhi0708](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/anzhi0708/32/4299_2.png) [@anzhi0708](https://discuss.ocaml.org/u/anzhi0708)\
**Post date:** [March 22, 2023, 12:33pm UTC](https://discuss.ocaml.org/t/help-regex-pattern-and-raw-strings/11747/1 "2023-03-22T12:33:34Z")

</div>

Hello folks! Another day, another noob question. Help wanted :3

I wrote this function to remove every ‘\n’ in the string.

```auto
let remove_newlines (str : string) : string =
    Str.global_replace (Str.regexp "\n") "" str

```

But then I discovered that it’s not the most elegant way to process a string like this

```auto
This is the first line.\nThis is the second line.

```

because there will be no space after the period mark and will make the text look less pretty.

So I tried

```auto
let remove_newlines (str : string) : string =
    Str.global_replace (Str.regexp {|\n(?![A-Z])|}) "" str

```

But I got no luck.

Also I’m not sure if I’m using `{|STRING|}` correctly. In Python, I use **raw string** in regexp like `r"Some\nText\n"` and I’m not familiar with OCaml’s raw strings.

What I want to achieve is:

```auto
>>> STRING = "Hello\nWorld, this i\ns your boi Anji"
>>> import re
>>> PATTERN=re.compile(r"\n(?![A-Z])")
>>> PATTERN.sub
PATTERN.sub( PATTERN.subn(
>>> PATTERN.sub
<built-in method sub of re.Pattern object at 0x1095cb510>
>>> PATTERN.sub("", STRING)
'Hello\nWorld, this is your boi Anji'
>>>

```

Sorry for posting another n00b question. Send help plz :3

---

<div class="post-metadata">

**Author:** ![anzhi0708](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/anzhi0708/32/4299_2.png) [@anzhi0708](https://discuss.ocaml.org/u/anzhi0708)\
**Post date:** [March 22, 2023, 4:06pm UTC](https://discuss.ocaml.org/t/help-regex-pattern-and-raw-strings/11747/2 "2023-03-22T16:06:33Z")

</div>

The problem was solved by writing a correct regexp

```auto
let remove_newlines (str : string) : string =
  let regex = Str.regexp "\n\\([a-z]\\)" in
  Str.global_replace regex " \\1" str

```

It turned out that it was my own problem for not having a good understanding of how to use regex. Sad!

---

<div class="post-metadata">

**Author:** ![mro](https://sea2.discourse-cdn.com/flex020/user_avatar/discuss.ocaml.org/mro/32/2496_2.png) [@mro](https://discuss.ocaml.org/u/mro)\
**Post date:** [March 22, 2023, 7:44pm UTC](https://discuss.ocaml.org/t/help-regex-pattern-and-raw-strings/11747/3 "2023-03-22T19:44:50Z")

</div>

you are not alone [xkcd: Perl Problems](https://xkcd.com/1171/)
