Search code examples
pythonexpressionmultiline

How can I count how many \n (new lines) using python and regular expressions?


Is there a way to count the number of lines in a set of text? For example:

text="hello what are you"\
"doing with yourself"\
"this weekend?"

I want to count the "\n". I know I could count this using regular python, but just wondering if there is a way to count this with Regular Expressions?


Solution

  • Side Note

    In your case there is no newline in text.

    Probably you wanted to define

    text = """hello what are you
    doing with yourself
    this weekend?"""
    

    Answer

    You don't need a regular expression.

    Just use text.count("\n")~

    Edit: Oh, nevermind. You need it to be a regex?

    len(re.findall("\n", text)) should work