Adam
Adam

Reputation: 44929

How do I make a regular expression that matches everything on a line after a given character?

If I have a String in JavaScript

key=value

How do I make a RegEx that matches key excluding =?

In other words:

var regex = //Regular Expression goes here
regex.exec("key=value")[0]//Should be "key"

How do I make a RegEx that matches value excluding =?

I am using this code to define a language for the Prism syntax highlighter so I do not control the JavaScript code doing the Regular Expression matching nor can I use split.

Upvotes: 1

Views: 126

Answers (4)

Diode
Diode

Reputation: 25135

var regex = /^[^=]*/;
regex.exec("key=value");

Upvotes: 0

Jason Orendorff
Jason Orendorff

Reputation: 45086

Well, you could do this:

/^[^=]*/     // anything not containing = at the start of a line
/[^=]*$/     // anything not containing = at the end of a line

It might be better to look into Prism's lookbehind property, and use something like this:

{
    'pattern': /(=).*$/,
    'lookbehind': true
}

According to the documentation this would cause the = character not to be part of the token this pattern matches.

Upvotes: 3

Ina
Ina

Reputation: 4470

.*=(.*)

This will match anything after =

(.*)=.*

This will match anything before =

Look into greedy vs ungreedy quantifiers if you expect more than one = character.

Edit: as OP has clarified they're using javascript:

var str = "key=value"; 
var n=str.match(/(.*)=/i)[1]; // before =
var n=str.match(/=(.*)/i)[1]; // after =

Upvotes: 0

burning_LEGION
burning_LEGION

Reputation: 13450

use this regex (^.+?)=(.+?$)

group 1 contain key

group 2 contain value

but split is better solution

Upvotes: 0

Related Questions