Showing posts with label Regex. Show all posts
Showing posts with label Regex. Show all posts

Friday, 24 January 2025

Javascript extract time from date string using regex

 const paragraph = '2016-06-06 13:27:39';

const regex = /((?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$)/gm;

const found = paragraph.match(regex);

Friday, 21 June 2024

JS remove regex

function removeHtmlTags(str) { return str.replace(/<\/?[^>]+(>|$)/g, ""); } 

Tuesday, 3 October 2023

Regex to test if gmail, javascript implementation

 https://stackoverflow.com/questions/16200965/regular-expression-validate-gmail-addresses


/
^[\w.+\-]+@gmail\.com$
/
gm
^ asserts position at start of a line
Match a single character present in the list below
[\w.+\-]
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
\w matches any word character (equivalent to [a-zA-Z0-9_])
.+
matches a single character in the list .+ (case sensitive)
\- matches the character - with index 4510 (2D16 or 558) literally (case sensitive)
@gmail
matches the characters @gmail literally (case sensitive)
\. matches the character . with index 4610 (2E16 or 568) literally (case sensitive)
com
matches the characters com literally (case sensitive)
$ asserts position at the end of a line
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)


https://regex101.com/codegen?language=javascript

const regex = /^[\w.+\-]+@gmail\.com$/gm;
regex.test('saddasd');

Monday, 13 September 2021

Regex find out trailling comma in end of json

 (,)(\s*}\s*)(?=\n|,\n|,\"\w|\})


{'test':'12', 'test3':'123', 'test' : { 'try':12, 'test':321},}


https://regex101.com/

Monday, 9 August 2021

Regex101 difference beteween [] vs [^] AND JS usage of regex

 [.......]  means to match anything provided in side of brackets

for example 




[^ .... ] means to match anything other than provided in side of brackets 




Javascript usage of abovce concept :

https://stackoverflow.com/questions/6555182/remove-all-special-characters-except-space-from-a-string-using-javascript

// Javascript string.replace('TargetInsideOfString', 'Replacement');

const string = "abc's test#s";
// In here TargetInsideOfString is regex pattern which is match anything in the provided brackets. 
// In this case special symbols provided in brackets, then those special symbol are replaced by ''
//  which means to remove them
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
// In here TargetInsideOfString is regex pattern which is match anything  
// other than the items in the  provided brackets. 
// In this case anything other than small case letter, upper case letter and 0-9 numbers
//  then those other things are replaced by '' 
// which means to remove them
string = string.replace(/[^a-zA-Z0-9]/g, '');






Friday, 23 July 2021

Javascript regex difference between match and exec, and test, and regex to get : separated key values with comma in end from string

 difference between JS exec and match


https://stackoverflow.com/questions/9214754/what-is-the-difference-between-regexp-s-exec-function-and-string-s-match-fun


exec with a global regular expression is meant to be used in a loop, as it will still retrieve all matched subexpressions. So:

var re = /[^\/]+/g;
var match;

while (match = re.exec('/a/b/c/d')) {
    // match is now the next match, in array form.
}

// No more matches.
JS Regex Test

https://www.w3schools.com/jsref/jsref_regexp_test.asp

The test() method tests for a match in a string.

This method returns true if it finds a match, otherwise it returns false.


Search a string for the character "e":

var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);

String.match does this for you and discards the captured groups. 

Match returns an array



Regex to find : separated key value pairs with comma in the end


/((?:"[^"]*"|[^:,])*):((?:"[^"]*"|[^,])*)/gm



https://stackoverflow.com/questions/37157779/regexp-to-get-text-in-a-key-value-pair-separated-by-a-colon

Thursday, 29 October 2020

Regex 101 part2


https://www.sitepoint.com/demystifying-regex-with-practical-examples/

 Scenario:

  • 6 to 12 characters in length
  • Must have at least one uppercase letter
  • Must have at least one lower case letter
  • Must have at least one digit
  • Should contain other characters

Pattern:

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,12}$

This expression is based on multiple positive lookahead (?=(regex)). The lookahead matches something followed by the declared (regex). The order of the conditions doesn’t affect the result. Lookaround expressions are very useful when there are several conditions.
We could also use the negative lookahead (?!(regex)) to exclude some character ranges. For example, I could exclude the % with (?!.*#).

  1. ^ asserts position at start of the string
  2. (?=.*[a-z]) positive lookahead, asserts that the regex .*[a-z] can be matched:
    • .* matches any character (except newline) between zero and unlimited times
    • [a-z] matches a single character in the range between a and z (case sensitive)
  3. (?=.*[A-Z]) positive lookahead, asserts that the regex .*[A-Z] can be matched:
    • .* matches any character (except newline) between zero and unlimited times
    • [A-Z] matches a single character between A and Z (case sensitive)
  4. (?=.*\d) positive lookahead, asserts that the regex *\dcan be matched:
    • .* matches any character (except newline) between zero and unlimited times
    • \d matches a digit [0-9]
  5. .{6,12} matches any character (except newline) between 6 and 12 times
  6. $ asserts position at end of the string

Matching URL

URL match

Scenario:

  • Must start with http or https or ftp followed by ://
  • Must match a valid domain name
  • Could contain a port specification (http://www.sitepoint.com:80)
  • Could contain digit, letter, dots, hyphens, forward slashes, multiple times

Pattern:

^(http|https|ftp):[\/]{2}([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4})(:[0-9]+)?\/?([a-zA-Z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~]*)

The first scenario is pretty easy to solve with ^(http|https|ftp):[\/]{2}.
To match the domain name we need to bear in mind that to be valid it can only contain letters, digits, hyphen and dots. In my example, I limited the number of characters after the punctuation from 2 to 4, but could be extended for new domains like .rocks or .codes. The domain name is matched by ([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}).

The optional port specification is matched by the simple (:[0-9]+)?.

A URL can contain multiple slashes and multiple characters repeated many times (see RFC3986), this is matched by using a range of characters in a group ([a-zA-Z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~]*).
It’s really useful to match every important element with a group capture (), because it will return only the matches we need. Remember that certain characters need to be escaped with \.

Below, every single subpattern explained:

  1. ^ asserts position at start of the string
  2. capturing group (http|https|ftp), captures http or https or ftp
  3. : escaped character, matches the character : literally
  4. [\/]{2} matches exactly 2 times the escaped character /
  5. capturing group ([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4}):
    • [a-zA-Z0-9\-\.]+ matches one and unlimited times character in the range between a and z, A and Z, 0 and 9, the character - literally and the character . literally
    • \. matches the character . literally
    • [a-zA-Z]{2,4} matches a single character between 2 and 4 times between a and z or A and Z (case sensitive)
  6. capturing group (:[0-9]+)?:
    • quantifier ? matches the group between zero or more times
    • : matches the character : literally
    • [0-9]+ matches a single character between 0 and 9 one or more times
  7. \/? matches the character / literally zero or one time
  8. capturing group ([a-zA-Z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~]*):
    • [a-zA-Z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~]* matches between zero and unlimited times a single character in the range a-z, A-Z, 0-9, the characters: -._?,'/\+&amp;%$#=~.

Matching HTML TAG

HTML TAG match

Scenario:

  • The start tag must begin with < followed by one or more characters and end with >
  • The end tag must start with </ followed by one or more characters and end with >
  • We must match the content inside a TAG element

Pattern:

<([\w]+).*>(.*?)<\/\1>

Matching the start tag and the content inside it’s pretty easy with <([\w]+).*> and (.*?), but in the pattern above I have added a useful thing: the reference to a capturing group.
Every capturing group defined by parentheses () could be referred to using its position number, (first)(second)(third), which will allow for further operations.
The expression above could be explained as:

  • Start with <
  • Capture the tag name
  • Followed by one or more chars
  • Capture the content inside the tag
  • The closing tag must be </tag name captured before>

Including only two capture groups in the expression, the tag name and the content, will return a very clear match, a list of tag names with related content.

Let’s dig a little deeper and explain the subpatterns:

  1. < matches the character < literally
  2. capturing group ([\w]+) matches any word character a-zA-Z0-9_ one or more times
  3. .* matches any character (except newline) between zero or more times
  4. > matches the character > literally
  5. capturing group (.*?), matches any character (except newline), zero and more times
  6. < matches the characters < literally
  7. \/ matches the character / literally
  8. \1 matches the same text matched by the first capturing group: ([\w]+)
  9. > matches the characters > literally

Matching duplicated words

HTML TAG match

Scenario:

  • The words are space separated
  • We must match every duplication – non-consecutive ones as well

Pattern:

\b(\w+)\b(?=.*\1)

This regular expression seems challenging but uses some of the concept previously shown.
The pattern introduces the concept of word boundaries.

A word boundary \b mainly checks positions. It matches when a word character (i.e.: abcDE) is followed by a non-word character (Ie: -~,!).
Below you can find some example uses of word boundary to make it clearer:
– Given the phrase Regular expressions are awesome
– The pattern \bare\b matches are
– The pattern \w{3}\b could match the last three letters of the words: lar, ion, are, ome

The expression above could be explained as:

  • Match every word character followed by a non-word character (in our case space)
  • Check if the matched word is already present or not

Below you will find the explanation for each sub pattern:

  1. \b word boundary
  2. capturing group ([\w]+) matches any word character a-zA-Z0-9_
  3. \b word boundary
  4. (?=.*\1) positive lookahead assert that the following can be matched:
    • .* matches any character (except newline)
    • \1 matches same text as first capturing group

The expression will make more sense if we return all the matches instead of returning only the first one. See the PHP function preg_match_all for more information.