Regex empty string or number [duplicate] - angularjs

I have the following Regular Expression which matches an email address format:
^[\w\.\-]+#([\w\-]+\.)+[a-zA-Z]+$
This is used for validation with a form using JavaScript. However, this is an optional field. Therefore how can I change this regex to match an email address format, or an empty string?
From my limited regex knowledge, I think \b matches an empty string, and | means "Or", so I tried to do the following, but it didn't work:
^[\w\.\-]+#([\w\-]+\.)+[a-zA-Z]+$|\b

To match pattern or an empty string, use
^$|pattern
Explanation
^ and $ are the beginning and end of the string anchors respectively.
| is used to denote alternates, e.g. this|that.
References
regular-expressions.info/Anchors and Alternation
On \b
\b in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.
That is, \b is located:
Between consecutive \w and \W (either order):
i.e. between a word character and a non-word character
Between ^ and \w
i.e. at the beginning of the string if it starts with \w
Between \w and $
i.e. at the end of the string if it ends with \w
References
regular-expressions.info/Word Boundaries
On using regex to match e-mail addresses
This is not trivial depending on specification.
Related questions
What is the best regular expression for validating email addresses?
Regexp recognition of email address hard?
How far should one take e-mail address validation?

An alternative would be to place your regexp in non-capturing parentheses. Then make that expression optional using the ? qualifier, which will look for 0 (i.e. empty string) or 1 instances of the non-captured group.
For example:
/(?: some regexp )?/
In your case the regular expression would look something like this:
/^(?:[\w\.\-]+#([\w\-]+\.)+[a-zA-Z]+)?$/
No | "or" operator necessary!
Here is the Mozilla documentation for JavaScript Regular Expression syntax.

I'm not sure why you'd want to validate an optional email address, but I'd suggest you use
^$|^[^#\s]+#[^#\s]+$
meaning
^$ empty string
| or
^ beginning of string
[^#\s]+ any character but # or whitespace
#
[^#\s]+
$ end of string
You won't stop fake emails anyway, and this way you won't stop valid addresses.

\b matches a word boundary. I think you can use ^$ for empty string.

^$ did not work for me if there were multiple patterns in regex.
Another solution:
/(pattern1)(pattern2)?/g
"pattern2" is optional. If empty, not matched.
? matches (pattern2) between zero and one times.
Tested here ("m" is there for multi-line example purposes): https://regex101.com/r/mezfvx/1

Related

Split String at every dot except when some word appears

I'm really new into regex and currently getting some trouble to solve a problem. I will appreciate any help :)
Using ruby 2.4.2
The problem: Split a string at every dot, except when the asd word is after the dot
String: str = "qwer.qwer.asd"
Code: str.split(/\./)
Output: ["qwer", "qwer", "asd"]
The output should be: ["qwer", "qwer.asd"]
Use
str.split(/\.(?!asd\b)/)
The \.(?!asd\b) pattern matches any dot that is not followed with asd followed with a word boundary. The (?!asd\b) is a negative lookahead that fails the match if the lookahead pattern finds a match immediately to the right of the current location.
In case the "word" ends with a period or end of string, use
str.split(/\.(?!asd(?:\.|\z))/)
where (?:\.|\z) is a non-capturing group matching either a dot (\.) or (|) end of string (\z).
See the Ruby demo and a regex demo.

Escaping square brackets when using LIKE operator in sql [duplicate]

I am trying to filter items with a stored procedure using like. The column is a varchar(15). The items I am trying to filter have square brackets in the name.
For example: WC[R]S123456.
If I do a LIKE 'WC[R]S123456' it will not return anything.
I found some information on using the ESCAPE keyword with LIKE, but how can I use it to treat the square brackets as a regular string?
LIKE 'WC[[]R]S123456'
or
LIKE 'WC\[R]S123456' ESCAPE '\'
Should work.
Let's say you want to match the literal its[brac]et.
You don't need to escape the ] as it has special meaning only when it is paired with [.
Therefore escaping [ suffices to solve the problem. You can escape [ by replacing it with [[].
I needed to exclude names that started with an underscore from a query, so I ended up with this:
WHERE b.[name] not like '\_%' escape '\' -- use \ as the escape character
Here is what I actually used:
like 'WC![R]S123456' ESCAPE '!'
The ESCAPE keyword is used if you need to search for special characters like % and _, which are normally wild cards. If you specify ESCAPE, SQL will search literally for the characters % and _.
Here's a good article with some more examples
SELECT columns FROM table WHERE
column LIKE '%[[]SQL Server Driver]%'
-- or
SELECT columns FROM table WHERE
column LIKE '%\[SQL Server Driver]%' ESCAPE '\'
According to documentation:
You can use the wildcard pattern matching characters as literal
characters. To use a wildcard character as a literal character,
enclose the wildcard character in brackets.
You need to escape these three characters %_[:
'5%' LIKE '5[%]' -- true
'5$' LIKE '5[%]' -- false
'foo_bar' LIKE 'foo[_]bar' -- true
'foo$bar' LIKE 'foo[_]bar' -- false
'foo[bar' LIKE 'foo[[]bar' -- true
'foo]bar' LIKE 'foo]bar' -- true
If you would need to escape special characters like '_' (underscore), as it was in my case, and you are not willing/not able to define an ESCAPE clause, you may wish to enclose the special character with square brackets '[' and ']'.
This explains the meaning of the "weird" string '[[]' - it just embraces the '[' character with square brackets, effectively escaping it.
My use case was to specify the name of a stored procedure with underscores in it as a filter criteria for the Profiler. So I've put string '%name[_]of[_]a[_]stored[_]procedure%' in a TextData LIKE field and it gave me trace results I wanted to achieve.
Here is a good example from the documentation:
LIKE (Transact-SQL) - Using Wildcard Characters As Literals
There is a problem in that while
LIKE 'WC[[]R]S123456'
and
LIKE 'WC\[R]S123456' ESCAPE '\'
both work for SQL Server, neither work for Oracle.
It seems that there isn't any ISO/IEC 9075 way to recognize a pattern involving a left brace.
Instead of '\' or another character on the keyboard, you can also use special characters that aren't on the keyboard. Depending o your use case this might be necessary, if you don't want user input to accidentally be used as an escape character.
Use the following.
For user input to search as it is, use escape, in that it will require the following replacement for all special characters (the below covers all of SQL Server).
Here a single quote, "'" ,is not taken as it does not affect the like clause as it is a matter of string concatenation.
The "-" & "^" & "]" replace is not required as we are escaping "[".
String FormattedString = "UserString".Replace("ð","ðð").Replace("_", "ð_").Replace("%", "ð%").Replace("[", "ð[");
Then, in SQL Query it should be as following. (In parameterised query, the string can be added with patterns after the above replacement).
To search an exact string.
like 'FormattedString' ESCAPE 'ð'
To search start with a string:
like '%FormattedString' ESCAPE 'ð'
To search end with a string:
like 'FormattedString%' ESCAPE 'ð'
To search containing with a string:
like '%FormattedString%' ESCAPE 'ð'
And so on for other pattern matching. But direct user input needs to be formatted as mentioned above.

Regex pattern matching for input type time

To check whether input type "time" field is completed (09:00am) I have used a regular expression.
ng-pattern="\b((1[0-2]|0?[1-9]):([0-5][0-9]) ([AaPp][Mm]))"
But in the same regular expression I want to check whether the input field is empty. For further information, time field can be empty or completed (ex: )(09:30am)
Can anyone help me regarding this..
In an ng-pattern, you need to use
ng-pattern="/^(?:(?:1[0-2]|0?[1-9]):[0-5]\d\s*[AaPp][Mm])?$/"
and if you need to avoid leading/trailing spaces, also add ng-trim="false".
See this regex demo.
The (?:...)? optional non-capturing group is a wrapper for the whole pattern that becomes optional, i.e. can match an empty string.
The ^ anchor will only match at the start of the string, and $ will anchor the match at the end of the string, so that an entire string should match.
In case somebody is looking for a regex for European time format (00:00-23:59), as i was, here is the regex for that:
^(?:1[0-9]|2[0-3]|0?[0-9]):[0-5]\d{1}?$
Hope this helps somebody save a minute or two.

Comma delimited string to array using regular expressions

I have a string: strString = first,last,,4443334444
I want to use regular expression to split this string into an array.
I'm using this regular expression [\""].+?[\""]|[^,]+ but it is ignoring the space after the word last.
So, my array is looking something like this:
[0] => first
[1] => last
[2] => 4443334444
instead of:
[0] => first
[1] => last
[2] =>
[3] => 4443334444
I would like to keep the space.
Any help would be appreciated.
You may use
"[^"\\]*(?:\\.[^"\\]*)*"|[^,]+|(?<=^|,)(?=$|,)‌​
See the regex demo
The expression consists of
"[^"\\]*(?:\\.[^"\\]*)*" - a double quoted string literal with escape sequence support
| - or
[^,]+ - 1 or more characters other than ,
| - or
(?<=^|,)(?=$|,)‌​ - any empty string that is either between commas, or between the start/end of string and a comma.
A couple of issues with your expression.
First [\""] is redundant, use ["] or better " (without the
character class) instead.
Second, your actual problem is due to
the + operator which requires at least one character (but
there's none between the commas, thus disallowing empty fields).
Third, this is probably some CSV output, so why not use
explode() or similar functions?
If you insist on using a regular expression, you might get along with:
".*?"|[^,]*
See a demo on regex101.com.
Not sure if there's a way to get the element between the two commas, since there's no regex expression for it. The best I could come up with is:
str.match(/(?:[^,]+)|,,/g)
=> ["first", "last", ",,", "4443334444"]
But you'll need to translate the ",," into an empty string.
Is there a reason why you're using regex? Does your language have a .split() function? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

.NET Regex for SQL Server string... but not Unicode string?

I'm trying to build a .NET regex to match SQL Server constant strings... but not Unicode strings.
Here's a bit of SQL:
select * from SomeTable where SomeKey = 'abc''def' and AnotherField = n'another''value'
Note that within a string two single quotes escapes a single quote.
The regex should match 'abc''def' but not n'another''value'.
I have a regex now that manages to locate a string, but it also matches the Unicode string (starting just after the N):
'('{2})*([^']*)('{2})*([^']*)('{2})*'
Thanks!
This pattern will do most of what you are looking to do:
(?<unicode>n)?'(?<value>(?:''|[^'])*)'
The upside is that it should accurately match any number of escaped quotes. (SomeKey = 'abc''''def''' will match abc''''def''.)
The downside is it also matches Unicode strings, although it captures the leading n to identify it as a Unicode string. When you process the regular expression, you can ignore matches where the match group "unicode" was successful.
The pattern creates the following groups for each match:
unicode: Success if the string is a Unicode string, fails to match if ASCII
value: the string value. escaped single quotes remain escaped
If you are using .NET regular expressions, you could add (?(unicode)(?<-value>)) to the end of the pattern to suppress matching the value, although the pattern as a whole would still match.
Edit
Having thought about it some more, the following pattern should do exactly what you wanted; it will not match Unicode strings at all. The above approach might still be more readable, however.
(?:n'(?:''|[^'])*'[^']*)*(?<!n)'(?<value>(?:''|[^'])*)'

Resources