Regex: Find lines that NOT contains curly brackets

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To find lines that do not contain curly brackets using regular expressions, you can use a negative lookahead assertion. In most regex engines, the syntax for a negative lookahead is (?!pattern), which means "not followed by the specified pattern." Here's how you can use it to find lines without curly brackets:

Regex Pattern: ^(?:(?!{).)*$

Explanation:

  • ^ asserts the start of the line.
  • (?: ... ) is a non-capturing group.
  • (?!{) is the negative lookahead, ensuring that the line is not followed by an opening curly brace {.
  • . matches any character except a newline.
  • * repeats the previous group zero or more times.
  • $ asserts the end of the line.

This pattern will match any line that does not contain any curly brackets. Here's a Python example using the re module:

python
import re

data = """
Line 1: This line contains { curly bracket.
Line 2: This line does not contain curly brackets.
Line 3: This line contains } another curly bracket.
Line 4: This line does not have any curly brackets.
"""


pattern = r'^(?:(?!{).)*$'

matches = re.findall(pattern, data, re.MULTILINE)
print(matches)

Output:

vbnet
['Line 2: This line does not contain curly brackets.', 'Line 4: This line does not have any curly brackets.']

As you can see, lines 2 and 4 are the lines that do not contain curly brackets.