Reputation: 44929
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
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
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
Reputation: 13450
use this regex (^.+?)=(.+?$)
group 1 contain key
group 2 contain value
but split is better solution
Upvotes: 0