Andreas
Andreas

Reputation: 193

Brackets in Regular Expression

I'd like to compare 2 strings with each other, but I got a little problem with the Brackets. The String I want to seek looks like this:

CAPPL:LOCAL.L_hk[1].vorlauftemp_soll

Quoting those to bracket is seemingly useless.

I tried it with this code

var regex = new RegExp("CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll","gi");
var value = "CAPPL:LOCAL.L_hk[1].vorlauftemp_soll";
regex.test(value);

Somebody who can help me??

Upvotes: 0

Views: 2328

Answers (3)

Arseni Mourzenko
Arseni Mourzenko

Reputation: 52321

In value, you have (1) instead of [1]. So if you expect the regular expression to match and it doesn't, it because of that.

Another problem is that you're using "" in your expression. In order to write regular expression in JavaScript, use /.../g instead of "...".

You may also want to escape the dot in your expression. . means "any character that is not a line break". You, on the other hand, wants the dot to be matched literally: \..

Upvotes: 2

Kobi
Kobi

Reputation: 138007

It is useless because you're using string. You need to escape the backslashes as well:

var regex = new RegExp("CAPPL:LOCAL.L_hk\\[1\\].vorlauftemp_soll","gi");

Or use a regex literal:

var regex = /CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll/gi

Unknown escape characters are ignored in JavaScript, so "\[" results in the same string as "[".

Upvotes: 5

Quentin
Quentin

Reputation: 943480

You are generating a regular expression (in which [ is a special character that can be escaped with \) using a string (in which \ is a special character).

var regex = /CAPPL:LOCAL.L_hk\[1\].vorlauftemp_soll/gi;

Upvotes: 1

Related Questions