Regular Expression in Javascript for finding parameters - javascript

I'm trying to write a regular expression in javascript to catch all named parameters in PostgreSQL string to put them in table
lets say we have
var query="SELECT table.data FROM table JOIN table2 ON table2.id=table.id_tab2 WHERE table2.field <> :parm1::int GROUP BY table.data HAVING table.data position(:docType::text in document_type) <> 0
var tab=new Array();
//
I need rs to put into tab all parameters: "param1::int" and "docType::text"
I tried do it myself but with no success :(
http://regexr.com?31nok

something like this? :(\w+::\w+)

and (:[a-zA-Z0-9]+::[a-zA-Z0-9]+)

There can be weird things between a-Z, so just use [a-z] with case insensitive or [a-zA-Z]. I think you probably want a global match (find all results). Multi-line is something else, it makes . match \n which doesn't help you that I can see. Try this: http://regexr.com?31not

I don't know postgreSQL, but I think I got the gist of your question.
Is this correct: http://refiddle.com/2tc?

when i try :([^: ]+::[^: ]+) and (:[^: ]+::[^: ]+) i see no difference- colon is in match in both casec.
However i found some other way
(?!:)([a-z0-9_-]+::[a-z0-9_-]+)
works perfectly.
first part (?<=:) determine "Matches a group before your main expression without including it in the result."
Thanks you all for your answers ;)

Related

Rex match a string in JS

I have few set of strings as mentioned below
/v4/users/1
/v4/users/1/vehicles/1
/v4/users
/v4/users?page=1
I would like to get users in all four cases as output using regex in Javascript
I tried below in https://www.regextester.com/
(?<=/v4/).*.(?=/[^/]*/)
It doesn't seem to come up right.
Any help on this would be appreciated.
You were close with the positive lookbehind. This works:
'/v4/users/1/vehicles/1'.match(/(?<=\/v4\/)[^\/\?]*/)
This matches users because after the lookbehind you match everything until just before the next slash.
/\/v4\/(\w+)/g
This will put users in a capture group. If you want you can make it a named group as well.
You can try it here:
https://regex101.com/r/0OOr0g/1

How do I replace string within quotes in javascript?

I have this in a javascript/jQuery string (This string is grabbed from an html ($('#shortcode')) elements value which could be changed if user clicks some buttons)
[csvtohtml_create include_rows="1-10"
debug_mode="no" source_type="visualizer_plugin" path="map"
source_files="bundeslander_staple.csv" include cols="1,2,4" exclude cols="3"]
In a textbox (named incl_sc) I have the value:
include cols="2,4"
I want to replace include_cols="1,2,4" from the above string with the value from the textbox.
so basically:
How do I replace include_cols values here? (include_cols="2,4" instead of include_cols="1,2,4") I'm great at many things but regex is not one of them. I guess regex is the thing to use here?
I'm trying this:
var s = $('#shortcode').html();
//I want to replace include cols="1,2,4" exclude cols="3"
//with include_cols="1,2" exclude_cols="3" for example
s.replace('/([include="])[^]*?\1/g', incl_sc.val() );
but I don't get any replacement at all (the string s is same string as $("#shortcode").html(). Obviously I'm doing something really dumb. Please help :-)
In short what you will need is
s.replace(/include cols="[^"]+"/g, incl_sc.val());
There were a couple problems with your code,
To use a regex with String.prototype.replace, you must pass a regex as the first argument, but you were actually passing a string.
This is a regex literal /regex/ while this isn't '/actually a string/'
In the text you supplied in your question include_cols is written as include cols (with a space)
And your regex was formed wrong. I recomend testing them in this website, where you can also learn more if you want.
The code above will replace the part include cols="1,2,3" by whatever is in the textarea, regardless of whats between the quotes (as long it doesn't contain another quote).
First of all I think you need to remove the quotes and fix a little bit the regex.
const r = /(include_cols=\")(.*)(\")/g;
s.replace(r, `$1${incl_sc.val()}$3`)
Basically, I group the first and last part in order to include them at the end of the replacement. You can also avoid create the first and last group and put it literally in the last argument of the replace function, like this:
const r = /include_cols=\"(.*)\"/g;
s.replace(r, `include_cols="${incl_sc.val()}"`)

Why would the replace with regex not work even though the regex does?

There may be a very simple answer to this, probably because of my familiarity (or possibly lack thereof) of the replace method and how it works with regex.
Let's say I have the following string: abcdefHellowxyz
I just want to strip the first six characters and the last four, to return Hello, using regex... Yes, I know there may be other ways, but I'm trying to explore the boundaries of what these methods are capable of doing...
Anyway, I've tinkered on http://regex101.com and got the following Regex worked out:
/^(.{6}).+(.{4})$/
Which seems to pass the string well and shows that abcdef is captured as group 1, and wxyz captured as group 2. But when I try to run the following:
"abcdefHellowxyz".replace(/^(.{6}).+(.{4})$/,"")
to replace those captured groups with "" I receive an empty string as my final output... Am I doing something wrong with this syntax? And if so, how does one correct it, keeping my original stance on wanting to use Regex in this manner...
Thanks so much everyone in advance...
The code below works well as you wish
"abcdefHellowxyz".replace(/^.{6}(.+).{4}$/,"$1")
I think that only use ()to capture the text you want, and in the second parameter of replace(), you can use $1 $2 ... to represent the group1 group2.
Also you can pass a function to the second parameter of replace,and transform the captured text to whatever you want in this function.
For more detail, as #Akxe recommend , you can find document on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace.
You are replacing any substring that matches /^(.{6}).+(.{4})$/, with this line of code:
"abcdefHellowxyz".replace(/^(.{6}).+(.{4})$/,"")
The regex matches the whole string "abcdefHellowxyz"; thus, the whole string is replaced. Instead, if you are strictly stripping by the lengths of the extraneous substrings, you could simply use substring or substr.
Edit
The answer you're probably looking for is capturing the middle token, instead of the outer ones:
var str = "abcdefHellowxyz";
var matches = str.match(/^.{6}(.+).{4}$/);
str = matches[1]; // index 0 is entire match
console.log(str);

regex - How do I exclude "%" and "_"?

Im allowing numbers, letters, and special characters except for % and _ in my html textbox. I have the pattern /[a-zA-Z0-9!##$^&*()-+=]/. I think its not the best way to do it because I have to list all special characters except the two mentioned. Is there a way in which I don't have to list all special characters and don't include the two mentioned? BTW, Im using javascript regex.
For the demo please see http://jsfiddle.net/ce8Th/
Please help.
There's no need for that complex loop. Just call replace directly on the whole string:
$(this).val(function (i, v) {
return v.replace(/%|_/g, '');
});
Here's your fiddle: http://jsfiddle.net/ce8Th/1/
You could just do the reverse:
/[%_]/
if (pattern.test( ....
It's also nice to not use regex if you don't have to, not that it makes a big difference in this case:
if ("%_".split().indexOf(text.charAt(i)) > -1) {
A white list is always best. I would recommend keeping what you have except adding a length modifier and start and end characters:
/^[a-zA-Z0-9!##$^&*()-+=]+$/
Would I happen to be corrent in guessing that you are using this user input for a MySQL query involving LIKE to search for partial matches?
If so, don't exclude characters. Instead, escape them on the server-side. For instance:
$output = str_replace(Array("%","_"),Array("\\%","\\_"),$input);

How to search csv string and return a match by using a Javascript regex

I'm trying to extract the first user-right from semicolon separated string which matches a pattern.
Users rights are stored in format:
LAA;LA_1;LA_2;LE_3;
String is empty if user does not have any rights.
My best solution so far is to use the following regex in regex.replace statement:
.*?;(LA_[^;]*)?.*
(The question mark at the end of group is for the purpose of matching the whole line in case user has not the right and replace it with empty string to signal that she doesn't have it.)
However, it doesn't work correctly in case the searched right is in the first position:
LA_1;LA_2;LE_3;
It is easy to fix it by just adding a semicolon at the beginning of line before regex replace but my question is, why doesn't the following regex match it?
.*?(?:(?:^|;)(LA_[^;]*))?.*
I have tried numerous other regular expressions to find the solution but so far without success.
I am not sure I get your question right, but in regards to the regular expressions you are using, you are overcomplicating them for no clear reason (at least not to me). You might want something like:
function getFirstRight(rights) {
var m = rights.match(/(^|;)(LA_[^;]*)/)
return m ? m[2] : "";
}
You could just split the string first:
function getFirstRight(rights)
{
return rights.split(";",1)[0] || "";
}
To answer the specific question "why doesn't the following regex match it?", one problem is the mix of this at the beginning:
.*?
eventually followed by:
^|;
Which might be like saying, skip over any extra characters until you reach either the start or a semicolon. But you can't skip over anything and then later arrive at the start (unless it involves newlines in a multiline string).
Something like this works:
.*?(\bLA_[^;]).*
Meaning, skip over characters until a word boundary followed by "LA_".

Categories

Resources