Menu
  • HOME
  • TAGS

Converting PCRE to POSIX regular expression

Tag: mysql,regex,pcre,posix-ere

I am working on a MySQL database and noticed that it doesn't natively support PCRE (requires a plugin).

I wish to use these three for some data validation (these are actually the values given to the pattern attribute):

  1. ^[A-z\. ]{3,36}
  2. ^[a-z\d\.]{3,24}$
  3. ^(?=^.{4,}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$

How do I do this?
I looked on the web but couldn't find any concrete examples or answers. Also there seem to exist no utilities that could do this automatically.

I am aware that some times, such conversions are not exact and can produce differences but I am willing to try.

Best How To :

The MySQL docs state that:

MySQL uses Henry Spencer's implementation of regular expressions, which is aimed at conformance with POSIX 1003.2. MySQL uses the extended version to support pattern-matching operations performed with the REGEXP operator in SQL statements.

Ok, so we're talking about POSIX ERE.

This page lists the details between various regex flavors, so I'll use it as a cheatsheet.


  1. ^[A-z\. ]{3,36}

    You're using:

    • Anchors: ^
    • Character classes: [...]
    • The range quantifier: {n,m}

    All of these are supported out of the box in POSIX ERE, so you can use this expression as-is. But escaping the . in the character class is redundant, and A-z is most probably wrong in a character class (it includes [\]^_\`), so just write:

    ^[A-Za-z. ]{3,36}
    
  2. ^[a-z\d\.]{3,24}$

    This one uses \d as well, which is unsupported in POSIX ERE. So you have to write:

    ^[a-z0-9.]{3,24}$
    
  3. ^(?=^.{4,}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$

    Meh. You're using lookaheads. These are totally out of the scope for POSIX ERE, but you can work around this limitation by combining several SQL clauses for an equivalent logic:

    WHERE LENGTH(foo) >= 4
      AND foo REGEXP '[0-9]'
      AND foo REGEXP '[a-z]'
      AND foo REGEXP '[A-Z]'
      AND NOT foo REGEXP '[ \t\r\n]'
    

How to call MySQL view in Struts2 or Hibernate

java,mysql,hibernate,java-ee,struts2

You can simply create an Entity, that's mapping the database view: @Entity public class CustInfo { private String custMobile; private String profession; private String companyName; private Double annualIncome; } Make sure you include an @Id in your view as well, if that's an updatable view. Then you can simply use...

Finding embeded xpaths in a String

java,regex

Use {} instead of () because {} are not used in XPath expressions and therefore you will not have confusions.

C# - Can't connect to remote MySQL server

c#,mysql

When connecting to a MySQL-Database I always used the MySQL Connector you can get here: https://dev.mysql.com/downloads/connector/net/6.9.html You have to import the MySQL namespaces to your project and then you can use the MySQLConnection instead of the SQLConnection that is, as far as I know, only for MSSQL servers. http://www.codeproject.com/Tips/423233/How-to-Connect-to-MySQL-Using-Csharp...

Regex that allow void fractional part of number

c#,regex

Just get the dot outside of the captruing group and then make it as optional. @"[+-]?\d+\.?\d*" Use anchors if necessary. @"^[+-]?\d+\.?\d*$" ...

Please can someone help me understand the exec method for regular expressions?

javascript,regex

I don't understand why it would give me two hellos back? Because the first entry in the array is the overall match for the expression, which is then followed by the content of any capture groups the expression defines. Since the expression defines one capture group, you get back...

Fatal error in if stament [duplicate]

php,mysql,mysqli

Just change the condition to: if(isset($_REQUEST['userid']) && $_REQUEST['userid'] > $user_hack) isset tells is a variable is set, while this statement may be true or false, on which you cannot call isset function. Until you check if(isset($_REQUEST['userid'])), you cannot assign it to $userid variable....

compare today's date with unix timestamp value in database

php,mysql

If I understand correctly you have a unix timestamp in a varchar field and you can't change this. If you compare the unix timestamp directly you will only get results that match the exact second of the timestamp. You can use FROM_UNIXTIME() to convert the timestamp in a date value...

Get all prices with $ from string into an array in Javascript

javascript,regex,currency

It’s quite trivial: RegEx string.match(/\$((?:\d|\,)*\.?\d+)/g) || [] That || [] is for no matches: it gives an empty array rather than null. Matches $99 $.99 $9.99 $9,999 $9,999.99 Explanation / # Start RegEx \$ # $ (dollar sign) ( # Capturing group (this is what you’re looking for) (?: #...

Regex with whitespaces and preceding zeros

regex,sas

You can use this simplified regex: /^[\s0]*11\s*$/ ...

MySQL - How can I know my query is tuned?

mysql,performance,explain

Except for trivial queries, there is no way to know if you have the optimal query & indexes. Nor can you get a metric for how well designed the schema and application are. 3 seconds on a cold system for a 3-way JOIN with "Rows" of 409, 45, 1 is...

How to Match a string with the format: “20959WC-01” in php?

php,regex

$pattern = '! ^ # start of string \d{5} # five digits [[:alpha:]]{2} # followed by two letters - # followed by a dash \d{2} # followed by two digits $ # end of string !x'; $matches = preg_match($pattern, $input); ...

I Want to fetch SQL Records in MySQL of current Year

mysql

Try this: SELECT count(enq.`enquiryId`), Month(enq.`date`), Year(enq.`date`) FROM enquiry enq WHERE Year(enq.date)=somevalue --2015 for example GROUP BY MONTH(enq.`date`) ...

Retrieve Values As Column

mysql,sql

If types are fixed (just IMPRESSION and CLICK), you could use a query like this: SELECT headline, SUM(tracking_type='IMPRESSION') AS impressions, SUM(tracking_type='CLICK') AS clicks FROM tracking GROUP BY headline ...

Trying to rewrite mysql_* to pdo

php,mysql,pdo

I don't know the source of the array $arr = array();, but it is assigned to null before the insert query. So it means, literally you are inserting nothing into the database. So check your array well, maybe it was to be like $arr = array('name'=>'My Name', 'url'=>'url', 'email'=>'my email',...

How do I display my mysql table column headers in my php/html output?

php,html,mysql,table,data

Note: You can just make a single file out of it to achieve your wanted output Use mysql_real_escape_string() to sanitize the passed-on value to prevent SQL injections You should use mysqli_* instead of the deprecated mysql_* API Form them in a single file like this (display.php): <html> <form method="post" name="display"...

Swing regular expression for phone number validation

java,regex

To only allow digits, comma and spaces, you need to remove (, ) and -. Here is a way to do it with Matcher.find(): Pattern pattern = Pattern.compile("^[0-9, ]+$"); ... if (!m.find()) { evt.consume(); } And to allow an empty string, replace + with *: Pattern pattern = Pattern.compile("^[0-9, ]*$");...

How to program a recurring billing/invoice system using PHP and MySQL

php,mysql

Cron sounds good. (Also it is worth to mention the MySQL Event Scheduler, but again I would go for a Cronjob) A copy would be something like this SQLFIDDLE: create table t ( id int, d date ); insert into t values( 0, CURDATE() ); insert into t values( 2,...

MySQL: Select several rows based on several keys on a given column

mysql,sql,database

If you are looking to find the records matching with both the criteria here is a way of doing it select `item_id` FROM `item_meta` where ( `meta_key` = 'category' and `meta_value` = 'Bungalow' ) or ( `meta_key` = 'location' AND `meta_value` = 'Lagos' ) group by `item_id` having count(*)=2 ...

regex - Match filename with or without extension

regex,logstash-grok

This is about as simple as I can get it: \b\w+\.?\w* See demo...

Reg ex matching a word

regex

You could use a negative lookahead which will exclude those having _FX following the initial alpha string ^ABD_DEF_GHIJ(?!_FX)(?:_\d{8})?$ see example here...

MySQL substring match using regular expression; substring contain 'man' not 'woman'

mysql,regex

A variant of n-dru pattern since you don't need to describe all the string: SELECT '#hellowomanclothing' REGEXP '(^#.|[^o]|[^w]o)man'; Note: if a tag contains 'man' and 'woman' this pattern will return 1. If you don't want that Gordon Linoff solution is what you are looking for....

Having two arrays in variable php

php,mysql,arrays,variables,multidimensional-array

The explode function is being used correctly, so your problem is further up. Either $data[$i] = mysql_result($result,$i,"data"); isn't returning the expected string "2015-06-04" from the database OR your function $data[$i] = data_eng_to_it_($data[$i]); isn't returning the expected string "04 June 2015" So test further up by echo / var_dump after both...

PHP: While loop not working after adjusting SELECT for SQL injection prevention

php,mysql,select,sql-injection,associative-array

You cannot bind column and table names, only data. You need to specify the table and then bind for your '%calendar weekday%'. $stmt = $conn->prepare("SELECT " . $selectLang . " FROM `TranslationsMain` WHERE `location` LIKE ? ORDER BY `sortOrder`, " . $selectedLang); $stmt->bind_param('s', $calendar_weekday); ...

How to create multiple jquery form fields and insert in mysql database, without using mysql_real_escape_string

javascript,php,jquery,mysql

Your problem has nothing to do with jQuery and the form. It is just highly recommended to prevent SQL injection, an attack in which an attacker injects SQL commands into your DB Query by posting it in your form. That's why any data that comes from an untrusted source (eg...

Can Rails deal with DB uniqueness without index?

mysql,ruby-on-rails,rdbms

Because there is no need for other ways. Under the hood it's all the same: when you define a UNIQUE constraint, a UNIQUE index is created on that table to enforce it. Question from DBA.SE: When should I use a unique constraint instead of a unique index? So for a...

Notice: Array to string conversion in “path of php file” on line 64

php,mysql,arrays,oracle

Curly brackets are your friend when inserting variables into double quoted strings: $main_query=oci_parse($connection,"INSERT INTO ROTTAN(NAME,ROLLNO) VALUES('{$array[$rs][0]}','{$array[$rs][1]}')"); ...

PHP / MySQLi: How to prevent SQL injection on INSERT (code partially working)

php,mysql,mysqli,sql-injection,sql-insert

In the New PHP code snippet, you are still vulnerable to injections. You are using a prepared statement in the insert part, but you are not actually using the preparations strengths correctly. When creating a prepared statement, you create a query in which you add placeholders instead of the raw...

How to create the javascript regular expression for number with some special symbols

javascript,regex

This matches all given examples as well: ^\$?\d+(?:[.,:]\d+)?%?$ See it in action: RegEx101 Please comment, if adjustment / further detail is required....

Using VLOOKUP formula or other function to compare two columns

mysql,excel,vba,date

If data in your first table starts at A2, and your other column starts at D2, then use in E2 =VLOOKUP(D2,$A$2:$B$17,2,0) Copy down as needed....

Ignore Group if LIMIT is not reached in MySQL

mysql

You can use the having clause to filter out the groups you don't need, keeping only the groups where there are more than 4 dates: SELECT Fruits, SUM(Ordered), Date FROM table GROUP BY Date HAVING COUNT(Date) > 4 ...

Regex to remove `.` from a sub-string enclosed in square brackets

c#,.net,regex,string,replace

To remove all the dots present inside the square brackets. Regex.Replace(str, @"\.(?=[^\[\]]*\])", ""); DEMO To remove dot or ?. Regex.Replace(str, @"[.?](?=[^\[\]]*\])", ""); ...

Php Mysql Query not working properly

php,mysql

No need to use union as it will give a lots of duplicate data What you want to achieve can be done with simple left join or inner join SELECT m.issue_name ,m.issue_type , m.priority ,m.status,m.description , m.start_date,m.end_date,m.duration, s.name as server_name,p.name as product_name from mod_networkstatus as m LEFT JOIN tblservers as...

SQL Group By multiple categories

php,mysql,sql,mysqli

Just include a case statement for the group by expression: SELECT (CASE WHEN Categories.name like 'Cat3%' THEN 'Cat3' ELSE Categories.name END) as name, sum(locations.name = 'loc 1' ) as Location1, sum(locations.name = 'loc 2') as Location2, sum(locations.name = 'loc 3') as Location3, count(*) as total FROM ... GROUP BY (CASE...

How many characters are visible like a space, but are not space characters?

php,regex

You can make use of a Unicode category \p{Zs}: Zs    Space separator $string = preg_replace('~\p{Zs}~u', ' ', $string); The \p{Zs} Unicode category class will match these space-like symbols: Character Name U+0020 SPACE U+00A0 NO-BREAK SPACE U+1680 OGHAM SPACE MARK U+2000 EN QUAD U+2001 EM QUAD U+2002 EN SPACE U+2003 EM SPACE...

How to write RegEx for inserting line break for line length more than 30 characters?

regex

Find what: ^(.{30}) Replace with: \1\n ...

PHP Regular Expressions Counting starting consonants in a string

php,regex

This is one way to do it, using preg_match: $string ="SomeStringExample"; preg_match('/^[b-df-hj-np-tv-z]*/i', $string, $matches); $count = strlen($matches[0]); The regular expression matches zero or more (*) case-insensitive (/i) consonants [b-df-hj-np-tv-z] at the beginning (^) of the string and stores the matched content in the $matches array. Then it's just a matter...

Symfony2 creating and persisting entity relationships

php,mysql,symfony2,doctrine2

When you create two entities with a one-to-one relationship, both entities need to be persisted either explicitly or by using cascade persist on one side of the relationship. You also need to explicitly set both sides of the relationship. Doctrine - Working with Associations - Transitive persistence / Cascade Operations...

Identify that a string could be a datetime object

python,regex,algorithm,python-2.7,datetime

What about fuzzyparsers: Sample inputs: jan 12, 2003 jan 5 2004-3-5 +34 -- 34 days in the future (relative to todays date) -4 -- 4 days in the past (relative to todays date) Example usage: >>> from fuzzyparsers import parse_date >>> parse_date('jun 17 2010') # my youngest son's birthday datetime.date(2010,...

MySQL Query returning strange values

php,mysql

You need to join by account_id and also question_id SELECT * FROM `quiz_questions` INNER JOIN `quiz_answers` ON `quiz_questions`.`account_id` = `quiz_answers`.`account_id` AND `quiz_questions`.`question_id` = `quiz_answers`.`question_id` WHERE `quiz_questions`.`account_id` = '1840979156127491' ORDER BY `quiz_questions`.`question_id` ASC LIMIT 5 ...

concatenate field names in a mysql update with inner join

php,mysql

You can try as per below- UPDATE products pr INNER JOIN sub_categories sc ON sc.id = pr.sub_category SET slug = REPLACE(TRIM(LOWER(CONCAT(sc.subcat_name,'.',products.product_name))),' ', '-'); ...

Query how often an event occurred at a given time

mysql,sql

This could be done using user defined variable which is faster as already mentioned in the previous answer. This needs creating incremental variable for each group depending on some ordering. And from the given data set its user and date. Here how you can achieve it select user, date, purchase_count...

If I export my database with phpmyadmin will it lock my tables or take my database down?

mysql,database,phpmyadmin

The answer is no, tables won't be locked, database won't be down. But, if your database is large and it takes long time to backup it, you can sometimes expect performance degradation(slow SQL queries from your application).

match line break except line begin with spcific word or blank line

regex,notepad++

Try this regex: (?<=[a-zA-Z])(\n) I used parentheses to capture the newline character. https://regex101.com/r/zS9pB4/3...

Temporarily Number Rows to Group by in MYSQL

mysql

You can do this using variables: select s.*, floor( ((@rn := @rn + 1) - 1) / 5) as group_number from sample s cross join (select @rn := 0) params order by date; ...

How to search images by name inside a folder?

php,mysql,image

This looks like a job for glob, which returns an array of file names matching a specified pattern. I'm aware of the other answer just posted, but let's provide an alternative to regex. According to the top comment on the docs page, what you could do is something like this:...

C# MySQL Parameters.AddWithValue

c#,mysql

You try to add all your 52 parameter and their values with one AddWithValue method. You can't do that. First of all, you need to define all your parameters in your command with your column names like; command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname, id, projectnummber....) VALUES (?name, ?id, ?projektnummer....)"; Then...

Get number from string

regex

Use \d+ to match one or more digits. \b(?:http:\/\/)?(?:www\.)?example\.com\/g\/(\d+)\/\w put http:// and www. inside a capturing or non-caturing group and then make it as optional by adding ? quantifier next to that group. For both http and https, it would be (?:https?:\/\/)? DEMO...

Regular Expression for whole world

regex,c#-4.0,vb6

You can use: Public\s+Const\s+g(?<Name>[a-zA-Z][a-zA-Z0-9]*)\s+=\s+(?<Value>False|True) demo ...

mysql detect field value change

mysql

Here's a way to do it using variables: SELECT id, `timestamp`, ver_fw FROM ( SELECT id, `timestamp`, ver_fw, IF ( @prev_ver <> ver_fw, IF (@prev_ver := ver_fw, 1, 1), IF (@prev_ver := ver_fw, 0, 0)) AS IsDifferent FROM tbl_geodata CROSS JOIN (SELECT @prev_ver := '-1') AS var WHERE imei LIKE...