Do not match regex - javascript

I am using this regex /\s*?left:\s*?-?\d+\.?\d*px;/im to find for example: left: 100.5px;.
The problem is that it also finds margin-left: 100px; or padding-left... I want it to not match words like -left but match left.
Any ideas?
EDIT: I am using this with javascript. I have made a simple jsfiddle for this. http://jsfiddle.net/WU7GV/3/ The goal is make "jupp" appear, but not "nope" with the same regex in both if-sentences

Option 1: Use start anchor:
/^left:\s*-?\d+\.?\d*px;/im
Option 2: If you cannot use start anchor as this might not be the actual start of input text then you can use word boundary with negative lookbehind like this:
/(?<!-)\bleft:\s*-?\d+\.?\d*px;/im
Live Demo: http://www.rubular.com/r/o1lsRU9mmE
Update: Javascript workaround for absence of negative lookahead:
var re=/\b.*?(left:\s*-?\d+\.?\d*px;)/igm;
function matchIt(str) {
repl = str.replace(re, function($0, $1) {
return $0 == $1? $0 : '';
});
return repl != ""? true : false;
}
console.log(matchIt('margin-left:100px;')); // false
console.log(matchIt('left:100px;')); // true
Live Demo: http://ideone.com/xt1kPH

Use a start-of-expression anchor
/^\s*?left:\s*?-?\d+\.?\d*px;/im
There can also be metrics other than px, but I'm sure you know that.

Use a beginning of string (and ending) anchor, like this:
/^\s*?left:\s*?-?\d+\.?\d*px;$/im

Use Word Boundries:
[^(left)]*\b\s*?(left:\s*?-?\d+\.?\d*px;)
So it looks for anything that isn't 'left', a word boundry, as described in the link above. Then your (group) to return what you want.
If you specify what language this regex is in, it'll help us answer your question. Otherwise, try out www.debuggex.com for an interactive regex debugger!

Try using this regex:
/([^-]left|^left):.*?;/im
This will match in case your string begins with "left" or one that contains "left" but not "-left".
If you aren't concerned with the units of your style, .*?; is a good shorthand to match everything from : to the nearest ; .
If you need to only match px and not %;, pt;, em !important;, etc..., keep your same regex after :, although I think the non-greedy spaces:
\s*?
are unnecessary, i.e., you could just use:
/([^-]left|^left):\s*-?\d+\.?\d*px;/im

Related

Negative match for earlier part of a regular expression

I'm trying to write a regular expression that matches filenames, such as:
image.png
image.svg
image.gif
However, I don't want it to match if my extension is preceded by .inline, like so:
image.inline.png
image.inline.svg
image.inline.gif
My current regular expression matches the first three, and is like so: /\.(gif|png|svg)$/ - however, I'm having trouble adding in the negative condition for a preceding .inline.
Thanks in advance for any advice.
I would also use a negative lookahead, but I would phrase it slightly differently:
var term = "image.inline.png";
var re = new RegExp("^(?!.*\\.inline\\.[^.]+$).*\\.(?:gif|png|svg)$");
if (re.test(term)) {
console.log("Valid");
} else {
console.log("Invalid");
}
You can use a negative lookahead to check for the preceeding .inline. See it in action here.
^\w+(?!\.inline)\.(gif|png|svg)$

RegEx don't match if starts with character?

I have this regex:
/(((\w+)|(\.\w+)|(\#\w+)|\*)(\[(.+(=".+"|\*".+"|\^".+"|))\])?(::|:)?)+(?=[ \S]*\{)/gm
Which I am trying to use to match CSS selectors. Consider this pseudo-code CSS input:
.main {
property: value;
}
.one, .two a[href$=".com"] {
.subclass {
property: value;
}
}
.test:before, .test:after:active {}
The pattern above will return the following matches:
['.body', '.one', '.two', 'a[href$=".com"]', '.subclass', '.test:before', '.test:after:active']
I am trying to modify the pattern so that psuedo selectors are not matched. So all the other matches should still be valid, but .test:before should just be .test and .test:after:active should also just match .test. I can't think of a way to do this without either a negative look-behind, or a way to not match if the first character is a :.
I'm implementing this in Node, and I don't want to lock my script to Node > 9.2.0 just to use negative look-behinds in my regex.
Any ideas would be greatly appreciated!
(?!.*:)(?:[.#]\w+|\w+\[.*\])
You could use something like this?
This uses a negative lookahead to ensure it doesn't capture anything with a colon beside it, as well as using a simplified version of your matcher for psuedo css elements.
See it working here

RegEx - Match Character only when it's not proceeded or followed by same character

How would I match the quotations around "text" in the string below and not around "TEST TEXT" using RegEx. I wanted just quotations only when they are by themselves. I tried a negative lookahead (for a second quote) but it still captured the second of the two quotes around TEST TEXT.
This is some "text". This is also some ""TEST TEXT""
Be aware that I need this to scale so sometimes it would be right in the middle of a string so something like this:
/(\s|\w)(\")(?!")/g (using $2...)
Would work in this example but not if the string was:
This is some^"text".This is also some ""TEST TEXT""
I just need quotation marks by themselves.
EDIT
FYI, this needs to be Javascript RegEx so lookbehind would not be an option for me for this one.
Since you have not tagged any particular flavor of regex I am takig liberty of using lookbehind also. You can use:
(?<!")"(?!")[^"]*"
RegEx Demo
Update: For working with Javascript you can use this regex:
/""[^"]*""|(")([^"]*)(")/
And use captured group # 1 for your text.
RegEx Demo
I'm not sure if I really understood well your needs. I'll post this answer to check if it helps you but I can delete it if it doesn't.
So, is this what you want using this regex:
"\w+?"
Working demo
By the way, if you just want to get the content within "..." you can use this regex:
"(\w+?)"
Working demo
You can't do this with a pure JavaScript regexp. I am going to eat my words now however, as you can use the following solution using callback parameters:
var regex = /""+|(")/g
replaced = subject.replace(regex, function($0, $1) {
if ($1 == "\"") return "-"; // What to replace to?
else return $0;
});
"This is some -text-. This is also some ""TEST TEXT"""
If you're needing the regex to split the string, then you can use the above to replace matches to something distinctive, then split by them:
var regex = /""+|(")/g
replaced = subject.replace(regex, function($0, $1) {
if ($1 == "\"") return "☺";
else return $0;
});
splits = replaced.split("☺");
["This is some ", "text", ". This is also some ""TEST TEXT"""]
Referenced by:http://www.rexegg.com/regex-best-trick.html

How would I make a regular expression that would mean /some string/ either followed by a line break or not?

function(input){
return input.replace(/teststring/ig, "adifferentstring");
}
I want to replace "teststring" and "teststring\n" with "adifferentstring"
In regex, to match a specific character you can place it in brackets:
[\n]
To make the match "optional", you can follow it with a ?:
[\n]?
In your exact example, your full regex could be:
teststring[\n]?
So, your function would look like:
function replace(input) {
return input.replace(/teststring[\n]?/ig, "adifferentstring");
}
I'd suggest going with matching characters in brackets as this makes for easy expansion; consider, for instance, that you want to match Window's newlines (a carriage-return + a newline):
teststring[\r\n]?
Try
function(input){
return input.replace(/teststring\n?/ig, "adifferentstring");
}
Try .replace(/teststring[\n]?/ig,"adifferentstring");
It would be something like this:
var re = /teststring([\n]?)/ig;
So then your replace statement would look about like this:
return input.replace(re,"adifferentstring");
Here's a fiddle showing the regex works.
And then a fiddle showing the replace operation working.
Edit:
Actually, thinking about the problem a little further, if your regex does match a carriage return or new line character, that would need to get put back into the replacing string. The same regex I posted originally will work but you will need this replace statement instead (with the $1 denoting the first group in parantheses.
return input.replace(re,"adifferentstring$1");
fiddle

How match a regex if it does not contain a particular word?

I want to write a regex in Python or JavaScript to match if the given string does not JUST contain the given word (e.g "any").
For example :
any : does not match
AnY : does not match
anyday : match
any day : match
blabla : match
If you also need words other that starting with "any" you can use a negative lookahead
^(?!any$).*$
This will match anything besides "any".
It is probably more efficient to not use a regex, this works as well:
def noAny(i):
i = i.lower().replace('any', '')
return len(i) > 0
Something like this:
/(any)(.+)/i
any.+
..and some text to make the 30char threshold
Use string.match(regexp) method in javascript for this purpose. See the code below:
<script type="text/javascript">
var str="source string contains YourWord";
var patt1=/YourWord/gi; // replace YourWord within this regex with the word you want to check.
if(str.match(patt1))
{
//This means there is "YourWord" in the source string str. Do the required logic accordingly.
}
else
{
// no match
}
</script>
Hope this helps...

Categories