How to use RegExReplace in Google Spreadsheet - regex

I'm trying to remove beggining numbers from a column in a Google Docs spreadsheet using regex. I can't get RegExReplace function to work. This is the error I get when I run/debug the code:
Missing ) after argument list. (line 14)
This is a part of my code (line 14 is the RegExReplace function line, bolded):
regexFormat = "^[0-9]+$";
replVal = value.RegExReplace(value; regexFormat; ""); //error here
rplc.setValue(replVal);
This is the official syntax: RegExReplace( text ; regular_expression ; replacement )
Anyone knows how to use this function? Thanks!

I don't know why the docs list a semicolon, but if you are doing it as a spreadsheet function, you still need to use commas. Try the following:
=REGEXREPLACE("What-A Crazy str3ng", "\W", "")
Which as expected, yields
WhatACrazystr3ng

I've found another solution for replacing with regexp in Google Docs Script:
var replace = '';//because we want to remove matching text
var regexp2 = new RegExp("[0-9]*[\.]*");//an example of regexp to do the job
var valcurat = value.replace(regexp2, replace);//working
As I did not find any solution for RegExReplace, I changed the method with replace(regexp, new_text). This one works.

This is just a guess but if the function is Javaish, maybe there are 2 forms.
Form 1:
myvar = RegExReplace(value; regexFormat; "");
Form2:
myvar = value.RegExReplace(regexFormat; "");

Related

calculate range of values entered by user Custom function Google Appscript

I want to use arrayformula for my custom function if possible because I want to input a range of values
I also get this error: TypeError: Cannot read property "0" from null.
Also, this: Service invoked too many times in a short time: exec qps. Try Utilities.sleep(1000) between calls
var regExp = new RegExp("Item: ([^:]+)(?=\n)");
var matches=new regExp(input);
return matches[0];
}
Really appreciated some help
Edit:
Based on the second picture, I also try using this regex formula to find word start with "Billing address"
But for the first picture, I used regex formula to find word start with "Item"
The error appears the same for both custom function.
If you want to use a custom function which finds all the strings that start with Item or item and extracts the contents from after the finding, you can use the code provided below. The regular expression is checked by using the match() function and returns the desired result; otherwise, it will return null.
function ITEM(input) {
var regEx = /(?:I|i)tem\s*(.*)$/;
var matches = input.match(regEx);
if (matches && matches.length > 1) {
return matches[1];
} else {
return null;
}
}
If you want to use the RegExp like you did in the code you have shared, you should use \\ instead of \.
For checking and verifying the regular expressions you can use this site.
The Service invoked too many times in a short time: exec qps. Try Utilities.sleep(1000) between calls. error message you are getting is due to the fact that you are trying to call the custom function on too many cells - for example dragging the custom function on too many cells at once. You can check more about this error message here.

How can I strip a href attribute without the query?

Using Google Sheets, I'd like to grab a URL without a possible query from a "href" attribute. For example, get https://test.com from Test1 or Test1.
I've used the regex answer offered in https://stackoverflow.com/a/40426187/4829915 to remove the query string, and then extracted the actual URL.
Is there a way to do it in one formula?
Please see below what I did. In all of these examples the final output is https://test.com
A B C
1 \?[^\"]+ href="(.+)"
2 Test1 =REGEXREPLACE(A2, B$1, "") =REGEXEXTRACT(B2, C$1)
3 Test2 =REGEXREPLACE(A3, B$1, "") =REGEXEXTRACT(B3, C$1)
4 Test3 =REGEXREPLACE(A4, B$1, "") =REGEXEXTRACT(B4, C$1)
In this answer, I would like to propose 2 patterns. In the 1st pattern, it uses REGEXEXTRACT. In the 2nd pattern, it uses a custom function using Google Apps Script (This is a sample.).
Pattern 1: Using formula
=REGEXEXTRACT(A2, C1)
where C1 is href="(.+?)[\?"]
Pattern 2: Using custom function
When you use this, please copy and paste the script to the script editor. Then please use it at a cell like =getUrl(A2).
function getUrl(value) {
var obj = XmlService.parse(value.replace(/&/g, ";"));
var url = obj.getRootElement().getAttribute("href").getValue();
return url.split("?")[0];
}
Results:
References:
REGEXEXTRACT
XmlService

How to remove text inside of parentheses with VB script RegExp

I am using a labeling software and I don't want any text inside of parentheses to display on the labels. Here is what I have so far
Function RemovePara(TextToBeEdited)
Set myRegEx = New RegExp
myRegEx.IgnoreCase = True
myRegEx.Global = True
myRegEx.Pattern = "\(([a-z]+?)\)(.+)"
Set RemovePara = myRegEx.Replace(txt, "")
End Function
Now I'm pretty new to this, and when I try to save this code in the labeling software it says "The script did not read the "Value" property, which means the current specified data source was ignored. This may not be what you intended" I had the text I field name I want edited where "TextToBeEdited" is at. What am I missing here?
You could use lookaround assertions.
myRegEx.Pattern = "(?<=\()[^()]*(?=\))"
Set RemovePara = myRegEx.Replace(txt, "")
DEMO

As3 Regex or alternative to split strings

i have a html page , i use regex to remove all html tags from the page and extract the text using the below code.
var foo = loader.data.replace(/<.*?>/g, "");
var bar:Array = foo.split("Total");
foo = foo.split(bar[0]);
trace(foo);
And using the same code lines below the replace method i remove every string before the word "TOTAL". It does the job perfectly but now i want to apply and other split to get contents after "TOTAL" and remove the Content after "BYTES".
So when i try to split it up again with
var bar2:Array = foo.split("BYTES");
foo = foo.split(bar2[0]);
Flash returns a error saying SPLIT is a not a valid method :S
I tried several other ways , ( REPLACE ) but still flash produces errors.
Can Anyone help me to get through this ?
Thank you
".split()" is a method of String. When you did the assignment below:
foo = foo.split(bar[0]);
foo became an array, and thus the call
var bar2:Array = foo.split("BYTES");
was being made to an array, which is invalid (no such method)
What you want instead is this:
var foo = loader.data.replace(/<.*?>/g, "");
trace(foo);
var result = foo.split("Total")[1].split("BYTES")[0];
trace(result);

How do I use regex in a SQLite query?

I'd like to use a regular expression in sqlite, but I don't know how.
My table has got a column with strings like this: "3,12,13,14,19,28,32"
Now if I type "where x LIKE '3'" I also get the rows which contain values like 13 or 32,
but I'd like to get only the rows which have exactly the value 3 in that string.
Does anyone know how to solve this?
As others pointed out already, REGEXP calls a user defined function which must first be defined and loaded into the the database. Maybe some sqlite distributions or GUI tools include it by default, but my Ubuntu install did not. The solution was
sudo apt-get install sqlite3-pcre
which implements Perl regular expressions in a loadable module in /usr/lib/sqlite3/pcre.so
To be able to use it, you have to load it each time you open the database:
.load /usr/lib/sqlite3/pcre.so
Or you could put that line into your ~/.sqliterc.
Now you can query like this:
SELECT fld FROM tbl WHERE fld REGEXP '\b3\b';
If you want to query directly from the command-line, you can use the -cmd switch to load the library before your SQL:
sqlite3 "$filename" -cmd ".load /usr/lib/sqlite3/pcre.so" "SELECT fld FROM tbl WHERE fld REGEXP '\b3\b';"
If you are on Windows, I guess a similar .dll file should be available somewhere.
SQLite3 supports the REGEXP operator:
WHERE x REGEXP <regex>
http://www.sqlite.org/lang_expr.html#regexp
A hacky way to solve it without regex is where ',' || x || ',' like '%,3,%'
SQLite does not contain regular expression functionality by default.
It defines a REGEXP operator, but this will fail with an error message unless you or your framework define a user function called regexp(). How you do this will depend on your platform.
If you have a regexp() function defined, you can match an arbitrary integer from a comma-separated list like so:
... WHERE your_column REGEXP "\b" || your_integer || "\b";
But really, it looks like you would find things a whole lot easier if you normalised your database structure by replacing those groups within a single column with a separate row for each number in the comma-separated list. Then you could not only use the = operator instead of a regular expression, but also use more powerful relational tools like joins that SQL provides for you.
A SQLite UDF in PHP/PDO for the REGEXP keyword that mimics the behavior in MySQL:
$pdo->sqliteCreateFunction('regexp',
function ($pattern, $data, $delimiter = '~', $modifiers = 'isuS')
{
if (isset($pattern, $data) === true)
{
return (preg_match(sprintf('%1$s%2$s%1$s%3$s', $delimiter, $pattern, $modifiers), $data) > 0);
}
return null;
}
);
The u modifier is not implemented in MySQL, but I find it useful to have it by default. Examples:
SELECT * FROM "table" WHERE "name" REGEXP 'sql(ite)*';
SELECT * FROM "table" WHERE regexp('sql(ite)*', "name", '#', 's');
If either $data or $pattern is NULL, the result is NULL - just like in MySQL.
My solution in Python with sqlite3:
import sqlite3
import re
def match(expr, item):
return re.match(expr, item) is not None
conn = sqlite3.connect(':memory:')
conn.create_function("MATCHES", 2, match)
cursor = conn.cursor()
cursor.execute("SELECT MATCHES('^b', 'busy');")
print cursor.fetchone()[0]
cursor.close()
conn.close()
If regex matches, the output would be 1, otherwise 0.
With python, assuming con is the connection to SQLite, you can define the required UDF by writing:
con.create_function('regexp', 2, lambda x, y: 1 if re.search(x,y) else 0)
Here is a more complete example:
import re
import sqlite3
with sqlite3.connect(":memory:") as con:
con.create_function('regexp', 2, lambda x, y: 1 if re.search(x,y) else 0)
cursor = con.cursor()
# ...
cursor.execute("SELECT * from person WHERE surname REGEXP '^A' ")
I don't it is good to answer a question which was posted almost an year ago. But I am writing this for those who think that Sqlite itself provide the function REGEXP.
One basic requirement to invoke the function REGEXP in sqlite is
"You should create your own function in the application and then provide the callback link to the sqlite driver".
For that you have to use sqlite_create_function (C interface). You can find the detail from here and here
An exhaustive or'ed where clause can do it without string concatenation:
WHERE ( x == '3' OR
x LIKE '%,3' OR
x LIKE '3,%' OR
x LIKE '%,3,%');
Includes the four cases exact match, end of list, beginning of list, and mid list.
This is more verbose, doesn't require the regex extension.
UPDATE TableName
SET YourField = ''
WHERE YourField REGEXP 'YOUR REGEX'
And :
SELECT * from TableName
WHERE YourField REGEXP 'YOUR REGEX'
SQLite version 3.36.0 released 2021-06-18 now has the REGEXP command builtin.
For CLI build only.
Consider using this
WHERE x REGEXP '(^|,)(3)(,|$)'
This will match exactly 3 when x is in:
3
3,12,13
12,13,3
12,3,13
Other examples:
WHERE x REGEXP '(^|,)(3|13)(,|$)'
This will match on 3 or 13
You may consider also
WHERE x REGEXP '(^|\D{1})3(\D{1}|$)'
This will allow find number 3 in any string at any position
You could use a regular expression with REGEXP, but that is a silly way to do an exact match.
You should just say WHERE x = '3'.
If you are using php you can add any function to your sql statement by using: SQLite3::createFunction.
In PDO you can use PDO::sqliteCreateFunction and implement the preg_match function within your statement:
See how its done by Havalite (RegExp in SqLite using Php)
In case if someone looking non-regex condition for Android Sqlite, like this string [1,2,3,4,5] then don't forget to add bracket([]) same for other special characters like parenthesis({}) in #phyatt condition
WHERE ( x == '[3]' OR
x LIKE '%,3]' OR
x LIKE '[3,%' OR
x LIKE '%,3,%');
You can use the sqlean-regexp extension, which provides regexp search and replace functions.
Based on the PCRE2 engine, this extension supports all major regular expression features. It also supports Unicode. The extension is available for Windows, Linux, and macOS.
Some usage examples:
-- select messages containing number 3
select * from messages
where msg_text regexp '\b3\b';
-- count messages containing digits
select count(*) from messages
where msg_text regexp '\d+';
-- 42
select regexp_like('Meet me at 10:30', '\d+:\d+');
-- 1
select regexp_substr('Meet me at 10:30', '\d+:\d+');
-- 10:30
select regexp_replace('password = "123456"', '"[^"]+"', '***');
-- password = ***
In Julia, the model to follow can be illustrated as follows:
using SQLite
using DataFrames
db = SQLite.DB("<name>.db")
register(db, SQLite.regexp, nargs=2, name="regexp")
SQLite.Query(db, "SELECT * FROM test WHERE name REGEXP '^h';") |> DataFrame
for rails
db = ActiveRecord::Base.connection.raw_connection
db.create_function('regexp', 2) do |func, pattern, expression|
func.result = expression.to_s.match(Regexp.new(pattern.to_s, Regexp::IGNORECASE)) ? 1 : 0
end