0

I'm trying to get the file name between two parentheses that can contain spaces between the name and any parentheses. example: ( file_name )

I used the regex:

(([A-Za-z_][A-Za-z0-9_]*)[ \t]*)

The problem is that, it matches the file_name with the spaces before and after it. I want to match the file_name without the spaces. Any help is appreciated.

mnabil
  • 695
  • 1
  • 5
  • 19

2 Answers2

1

You could use

\(\s*(\S+)\s*\)

and take the first group, see a demo on regex101.com.


Explained:
\(    # match ( literally
\s*   # zero or more whitespaces
(\S+) # capture anything not a whitespace, at least one character
\s*.  # same as above
\)    # match ) literally
Jan
  • 42,290
  • 8
  • 54
  • 79
1

Just add \s* outside the capturing parenthesis. (also you need to escape the outermost parenthesis if you want to match a litteral parenthesis) :

\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)
Eino Gourdin
  • 4,169
  • 3
  • 39
  • 67
  • Thanks Eino for your answer. It does not work with escaping the parentheses. Without escaping the parentheses, it gives me the file_name with the spaces before it and without the spaces after it. Now, we need to remove the spaces before it. – mnabil Oct 31 '18 at 12:58
  • Can you give us an example of exact string you want to match (are there parenthesis in there) ? I understood it's "( file_name )" and you want to match file_name – Eino Gourdin Oct 31 '18 at 13:22
  • I'm writing a parser that reads a file using Lex. When it founds "include ( file_name )", it extracts the file_name and opens it to continue reading from it. The "fopen" function gives an error if the file name contains spaces before or after. Thus, I want to extract the file name without any spaces before or after. – mnabil Oct 31 '18 at 13:29
  • Then something like this should work : `include\s*\(\s*([A-Za-z_][\w\.]*)\s*\)`. Cf [example on regex101](https://regex101.com/r/FOlK2Y/1/) – Eino Gourdin Oct 31 '18 at 14:00