Reputation: 1727
I'm wondering if variable length lookbehind assertions are supported in JavaScript's RegExp engine?
For example, I'm trying to match the string "variable length" in the string "[a lot of whitespaces and/or tabs]variable length lookbehind", and I have something like this but it does not go well in various RegExp testers:
^(?<=[ \t]+).+(?= lookbehind)
If it's an illegal pattern, what would be a good workaround to it? Thanks!
Upvotes: 1
Views: 1057
Reputation: 1074138
Javascript doesn't have look-behind at all. Steven Levithan has written up a few says to sort of mimic it, which may be helpful.
I don't quite understand your example, because it seems as though this would fit the bill:
/^\s+(.+)lookbehind$/
...which matches one or more whitespace chars followed by one or more of any character (in a capture group) followed by the word "lookbehind". Used like this:
var str = " variable length lookbehind";
var match = /^\s+(.+)lookbehind$/.exec(str);
yields this array:
match[0]: | variable length lookbehind|
match[1]: |variable length|
In Javascript, the first entry in the array is the entire matched string, and the subsequent entries are the capture groups.
But you clearly have a good grasp of regex, so I'm not sure that's what you're looking for...
Something to be aware of in this general area is that a number of implementations of RegExp engines in Javascript don't quite handle \s
correctly (they miss out matching some whitespace chars above the ASCII range); see the S_REGEXP_WHITESPACE_CHARACTER_CLASS_BUGGY test here.
Upvotes: 2
Reputation:
It shows numerous ways a trim can be done (none of which require a look-behind) and also compares the speed of the different approaches. If the end-goal includes stripping leading white-space, don't be afraid to break it down into multiple operations.
Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems - Jamie Zawinski
Upvotes: 2
Reputation: 2070
I don't know if this would help you with RegExp but if you want to remove whitespaces you can use a trim function
function trimAll(sString) {
while (sString.substring(0, 1) == ' ') {
sString = sString.substring(1, sString.length);
}
while (sString.substring(sString.length - 1, sString.length) == ' ') {
sString = sString.substring(0, sString.length - 1);
}
return sString;
}
Otherwise if you want to check string existance you can use indexOf IndexOf on StackOverflow.com
Upvotes: 2
Reputation: 8166
Javascript regex engine does not support lookbehinds, only lookaheads are supported. Here you can find a mimicking solution: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
Upvotes: 2