1

I want to match string ending with ')' . I use pattern :

 "[)]\b" or ".*[)]\b"

It should match the string :

x=main2.addMenu('Edit')

But it doesn't work. What is wrong ?

andio
  • 903
  • 3
  • 17
  • 30

3 Answers3

2

The \b only matches a position at a word boundary. Think of it as a (^\w|\w$|\W\w|\w\W) where \w is any alphanumeric character and \W is any non-alphanumeric character. The parenthesis is non-alphanumeric so won't be matched by \b.

Just match a parethesis, followed by the end of the string by using \)$

Zhewriix
  • 138
  • 10
  • Thanks , it's good explaination . I use this website : https://regex101.com . I tried that '$' and it works. But if i have multiline strings then i will match the last line. So maybe i have to break down that multiline first into separate lines. Or any other solution ? – andio Mar 08 '16 at 04:24
  • If you want to write a regex that matches multiple lines then you will need to add a modifier which depends on which language you're using. See [this](http://stackoverflow.com/q/159118/2516183) question. – Zhewriix Mar 09 '16 at 07:43
2

If you want to capture a string ending in ) (and not just find a trailing )), then you can use this in JS:

(.*?\)$)

(....) - captures the defined content;

.*? - matches anything up to the next element;

\)$ - a ) at the end of the string (needs to be escaped);

Regex101

sideroxylon
  • 3,977
  • 1
  • 18
  • 33
1

The \b word boundary is ambiguous: after a word character, it requires that the next character must a non-word one or the end of string. When it stands after a non-word char (like )) it requires a word character (letter/digit/underscore) to appear right after it (not the end of the string here!).

So, there are three solutions:

  • Use \B (a non-word boundary): .*[)]\B (see demo) that will not allow matching if the ) is followed with a word character
  • Use .*[)]$ with MULTILINE mode (add (?m) at the start of the pattern or add the /m modifier, see demo)
  • Emulate the multiline mode with an alternation group: .*[)](\r?\n|$) (see demo)
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397