0

I am trying to find a string between space and colon. For that I have the below regex expression which is giving me an 'invalid group name' error (same in python also):

(?<content>[^ :]*:$)

Here is RegexDemo

Same Expression has no error in PHP Demo.

Javascript expression :-

var reg = new RegExp("(?<content>[^ :]*):$", "g");`

Can anybody tell me why should be this?

Edit:

Sample Input:

DefVariable   変数名:配列「n]
DefVariable  変数名:string
DefVariable   変数名:int
DefVariable   変数名:decimal
DefVariable   変数名:日付
DefVariable   変数名:時間

Sample Output:

Could be match 変数名: from each line where instead of 変数名 any character will come.

Jankya
  • 966
  • 2
  • 12
  • 34
  • How do you call the result of your regex? – Docteur Apr 28 '15 at 06:15
  • @Docteur its giving error on var reg = new RegExp("(?[^ :]*):$", "g");` statement because of that its not proceed to next statement. the call is before result calling statement. – Jankya Apr 28 '15 at 06:20
  • Please see my demo with updated input. It should work for you! – Docteur Apr 28 '15 at 06:45
  • @Grundy: This is not just named capturing group issue, the anchor was not correctly used, too. There are several issues here, I believe. – Wiktor Stribiżew Apr 28 '15 at 07:09
  • @stribizhev, methinks main problem in OP _regex expression which is giving me an 'invalid group name' error_ and _Can anybody tell me why should be this?_ so it seems exactly duplicated – Grundy Apr 28 '15 at 07:12
  • @Grundy: I know, but then came the edits. Edits usually turn a question into some different question than at the beginning. – Wiktor Stribiżew Apr 28 '15 at 07:14
  • @stribizhev in edit simple provided input and output without diffrent question :-) – Grundy Apr 28 '15 at 07:16
  • @stribizhev anyway for marked duplicate just mine vote not enough – Grundy Apr 28 '15 at 07:18

2 Answers2

0

Your Regex is incorrect :

(?<content>[^ :]*:$)

A (?<group>) notation doesn't exist in Javascript. Only (numbered group), (?:non capturing) and lookarounds. If I understand correctly, you need this :

\s([^ :]*):$

See demo here.

Docteur
  • 1,235
  • 18
  • 34
0

You cannot use named capturing groups in JavaScript regex. You will have to use just a numbered one, like this:

 ([^ :]*:)

Also, you are using $ (end of string/line) anchor in your regex, but in your examples, there are still some characters after the full-width colon. Thus, the regex won't match even if you remove the named capture.

Explanation:

  • - A literal space
  • ([^:]*:) - A capturing group with a string that has no spaces and full-width colons, 0 or more size and , a full-width colon
  • $ - End of string/line.

See demo

In PHP, named groups exist., and you can use (?<name>...) or (?'name'). In Python, they also exist, but they are written in a bit different way: (?P<tag>...)

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563