The problem is I need to match a word say "match" in a string. It is very easy using the expression /(match)/gi |
Above expression is very easy. Now original problem is need to match word "match" not starting with any other word like 10 or 20 or any word. To do so we need to use negative lookbehind. Below is a complete regex that will match word match but not start with 10 or 20 or '. |
/(?<!(10|20))(?<!')(match)/gi |
Meaning of the above regex is will match a word match but not followed by 10 or 20 or ' Output of this regex is as below |
|
Explanation of this regex: |
|
Showing posts with label regex. Show all posts
Showing posts with label regex. Show all posts
Friday, June 22, 2018
A regex to match a substring that isn't followed by a certain other substring > Find Any Word Not Followed by a Specific Word > Regex Negative Lookbehind
Friday, January 5, 2018
Regex Domain Name Validation | Regex URL Validation
Domain Name Validation (Regex-101 Link)
^((https?):\/\/)?([a-zA-Z0-9_][-_a-zA-Z0-9]{0,62}\.)+([a-zA-Z0-9]{1,20})$
URL Validation (Regex-101 Link)
Thursday, December 21, 2017
Thursday, November 16, 2017
JavaScript Regex To Match Domain Name | Domain Validator Regex
Below is the required regex to validate any domain name, its simple so you can modify if you need to extend it.
^((http|https):\/\/)?([a-zA-Z0-9_][-_a-zA-Z0-9]{0,62}\.)+([a-zA-Z0-9]{1,10})$
^((http|https):\/\/)?([a-zA-Z0-9_][-_a-zA-Z0-9]{0,62}\.)+([a-zA-Z0-9]{1,10})$
Thursday, November 9, 2017
jQuery Number Text Field Validation Using Regex On Input Field
jQuery Number Text Field Validation Using Regex
Below is the full example of how to validate number using regex
var pattern = new RegExp("(^(\-?)([0-9]{0,12}?)(\\.)([0-9]){0,12}$)|(^(\-?)([0-9]){0,12}$)"); $(document.body).on("keypress", "input[type='text'].number", function (e) { if (e.which == 0 || e.which == 8) return true; var v = getTextFieldValue(this, String.fromCharCode(e.which)); $("div").html(v); return pattern.test(v); }); document.addEventListener("paste", function (e) { var v, f = $(e.target), ov = f.val(); if (window.clipboardData && window.clipboardData.getData) { // IE v = window.clipboardData.getData('Text'); } else if (e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.getData) { v = e.originalEvent.clipboardData.getData('text/plain'); } else if (e.clipboardData && e.clipboardData.getData) { v = e.clipboardData.getData('text/plain'); } v = getTextFieldValue(f[0], v); if (!pattern.test(v)) e.preventDefault(); $("div").html(v); }); function getTextFieldValue(input, nv) { var v = input.value, i = input.selectionStart, j = input.selectionEnd; if (i == 0 && j == v.length) return nv; else if (i != j || i > 0) return v.substr(0, i) + nv + v.substr(j); else if (i == 0) return nv + v; else return v + nv; } $("input[type='text'].number").focus();
And finally you can use below regex to test your number:
^[-+]?(?:\.[0-9]{1,12}|[0-9]{1,12}(?:\.[0-9]{0,12})?)(?:[eE][-+]?[0-9]{1,12})?$
You can experience above example in JsFiddle
You can also check in regex test environment
Thursday, November 2, 2017
JavaScript jQuery Phone Number Validation Using Regex Pattern
Below is the regex to check valid phone number:
Regex check result as below:
var regex = /(^(\+?[0-9]+)?((\s|\-|\.)[0-9]+)+$)|(^\(\+?[0-9]+\)((\s|\-|\.)[0-9]+)+$)|(^[0-9]+$)/i;
Regex check result as below:
+39 347 12 34 567 is valid = true
(+333)-696 900 is valid = true
(+333) -696 900 is valid = false
(+333)-696 900 is valid = true
(+333-696 900 is valid = false
+333-696 900 is valid = true
+333-696 900 is valid = true
+333-696 900 is valid = true
333-696 900 is valid = true
333-696 900 is valid = true
333-696 90 is valid = true
333-696 9 is valid = true
333-696 is valid = true
333-69 is valid = true
333-6 is valid = true
333- is valid = false
333 is valid = true
JavaScript | jQuery Validate Email Address Using Regex Pattern Check
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
And you can check your desired input by:
pattern.test("pritomkucse@gmail.com");
Wednesday, June 3, 2015
Validate URL Using Java & Regex
class UrlValidator { public static void main (String[] args) { check("http://google.com"); check("http://google.com?a=b#99"); check("http://google.com?a=b#99#sty"); check("http://www.google.com?a=1&b=2 / 3"); check("http://www.google.com?a=1&orderRate=orderRateUUID"); } public static void check(String url) { String Regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; Boolean matches = url.matches(Regex); if(matches) { System.out.println("URL (YES): " + url); } else { System.out.println("URL (NOT): " + url); } } }
URL (YES): http://google.com URL (YES): http://google.com?a=b#99 URL (YES): http://google.com?a=b#99#sty URL (NOT): http://www.google.com?a=1&b=2 / 3 URL (YES): http://www.google.com?a=1&orderRate=orderRateUUID
Friday, May 9, 2014
Java Replace Camel Case String With Another String In That Place
MainClass.java
package com.pkm; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass { public static String mainString = "PritomKumarMondal"; public static void main(String[] args) { System.out.println("Method: getString()"); System.out.println("\t" + getString()); System.out.println("Method: getString2()"); System.out.println("\t" + getString2()); System.out.println("Method: getString3()"); System.out.println("\t" + getString3()); System.out.println("Method: getString4()"); System.out.println("\t" + getString4()); System.out.println("Method: getString5()"); System.out.println("\t" + getString5()); } public static String getString() { System.out.println("\t" + MainClass.mainString); return MainClass.mainString.replaceAll("[^a-zA-Z0-9]+", "").replaceAll( String.format("%s|%s|%s", "(?<=[A-Z])(?=[a-z])", "(?<=[^A-Z])(?=[A-Z])", "(?<=[A-Za-z])(?=[^A-Za-z])" ), "." ).toLowerCase(); } public static String getString2() { System.out.println("\t" + MainClass.mainString); String string = MainClass.mainString.replaceAll( String.format("%s", "(?=[A-Z])(?=[A-Z])" ), "." ).toLowerCase(); string = string.replaceAll("[^a-zA-Z0-9.]+", ""); return string.startsWith(".") ? string.substring(1) : string; } public static String getString3() { System.out.println("\t" + MainClass.mainString); return MainClass.mainString.replaceAll( String.format("%s", "(?<=[^A-Z])(?=[A-Z])" ), "." ).toLowerCase().replaceAll("[^a-zA-Z0-9.]+", ""); } public static String getString4() { System.out.println("\t" + MainClass.mainString); String str1 = MainClass.mainString; str1 = str1.replaceAll("[A-Z]+", ".$0").toLowerCase().replaceAll("[^a-zA-Z0-9.]+", ""); str1 = str1.startsWith(".") ? str1.substring(1) : str1; return str1; } public static String getString5() { System.out.println("\t" + MainClass.mainString); String str1 = MainClass.mainString; Pattern pattern = Pattern.compile("[A-Z]+"); Matcher matcher = pattern.matcher(str1); StringBuffer output = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(output, "." + matcher.group().toLowerCase()); } matcher.appendTail(output); str1 = output.toString().replaceAll("[^a-zA-Z0-9.]+", ""); return str1.startsWith(".") ? str1.substring(1) : str1; } }
Output using: 'sUIKAm009Pritom KumarMondalUUID'
Method: getString() sUIKAm009Pritom KumarMondalUUID s.uika.m.009.p.ritom.k.umar.m.ondal.uuid Method: getString2() sUIKAm009Pritom KumarMondalUUID s.u.i.k.am009.pritom.kumar.mondal.u.u.i.d Method: getString3() sUIKAm009Pritom KumarMondalUUID s.uikam009.pritom.kumar.mondal.uuid Method: getString4() sUIKAm009Pritom KumarMondalUUID s.uikam009.pritom.kumar.mondal.uuid Method: getString5() sUIKAm009Pritom KumarMondalUUID s.uikam009.pritom.kumar.mondal.uuid
Output using: 'PritomKumarMondal'
Method: getString() PritomKumarMondal p.ritom.k.umar.m.ondal Method: getString2() PritomKumarMondal pritom.kumar.mondal Method: getString3() PritomKumarMondal pritom.kumar.mondal Method: getString4() PritomKumarMondal pritom.kumar.mondal Method: getString5() PritomKumarMondal pritom.kumar.mondal
Output using: 'Pritom KUMAR MonDAL'
Method: getString() Pritom KUMAR MonDAL p.ritom.kumarm.on.dal Method: getString2() Pritom KUMAR MonDAL pritom.k.u.m.a.r.mon.d.a.l Method: getString3() Pritom KUMAR MonDAL pritom.kumar.mon.dal Method: getString4() Pritom KUMAR MonDAL pritom.kumar.mon.dal Method: getString5() Pritom KUMAR MonDAL pritom.kumar.mon.dal
Java Regex to convert string to ascii code and ascii code to string back
MainClass.java
package com.pkm; import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass { public static void main(String[] args) { String str1 = "(=>THAI(คุณ), HINDI:(तुम मेरी हो), HANGERIO:(تو مال منی), CHINA:(您), ARBI(أنت), FARSI(شما)"; System.out.println("\n\nOriginal :: " +str1); Pattern pattern = Pattern.compile("([^\\x00-\\x7F])|([^A-Za-z0-9-_])"); StringBuffer output = new StringBuffer(); Matcher matcher = pattern.matcher(str1); while (matcher.find()) { String mString = matcher.group(0); String rep = String.format("[%d \\%s = %d]", mString.length(), mString, (int) mString.charAt(0)); String rep2 = String.format("&#%d;", (int) mString.charAt(0)); matcher.appendReplacement(output, rep2); } matcher.appendTail(output); System.out.println("Output :: " + output.toString()); pattern = Pattern.compile("\\&\\#\\d{2,}\\;"); matcher = pattern.matcher(output.toString()); output = new StringBuffer(); while (matcher.find()) { String mString = matcher.group(0); mString = mString.substring(2); mString = mString.substring(0, mString.length() - 1); mString = Character.toString((char) Integer.parseInt(mString)); matcher.appendReplacement(output, mString); } matcher.appendTail(output); System.out.println("Output :: " + output.toString()); } }
Output as follows:
Original :: (=>THAI(คุณ), HINDI:(तुम मेरी हो), HANGERIO:(تو مال منی), CHINA:(您), ARBI(أنت), FARSI(شما) Output :: &#40;=>THAI(คุณ), HINDI:(तुम मेरी हो), HANGERIO:(تو مال منی), CHINA:(您), ARBI(أنت), FARSI(شما) Output :: (=>THAI(คุณ), HINDI:(तुम मेरी हो), HANGERIO:(تو مال منی), CHINA:(您), ARBI(أنت), FARSI(شما)
Java code to convert string to ascii code and ascii code to string back
Saturday, November 23, 2013
java convert regular expression into string
It is easy to check a string with regular expression, but there is no direct method to generate string from regular expression. I hardly need it but found nothing. So I myself generated the following program to generate string using regular expression and check back the string with given regular expression. The program i generated will sufficient for normal expression. It will cover my back. It will not parse high level expression.
Output example using random regex generator
Regex: [a-z][a-z0-9]{8,10}@[a-z0-9]{5,9}.com Matches: [a-z][a-z0-9]{8,10}@[a-z0-9]{5,9}.com, String: bak65qvkpp@3qosue.com, Length: 21 Regex: [\w][\D]{0,10}[\d\W]{1,10}[abc.][abc09]{1,10} Matches: [\w][\D]*[\d\W]+[abc.][abc09]+, String: aLchJL,e’‘.c9bca, Length: 16 Regex: [A-Z]{4}-#%[\d]{3} Matches: [A-Z]{4}-#%[\d]{3}, String: BAKZ-#%114, Length: 10 Regex: www.[a-z][a-z0-9-_]{5,15}[a-z].com Matches: www.[a-z][a-z0-9-_]{5,15}[a-z].com, String: www.jj829x10cq9ngilk.com, Length: 24 Regex: 01[7856][0-9]{2}-[0-9]{6} Matches: 01[7856][0-9]{2}-[0-9]{6}, String: 01700-736202, Length: 12
StringRegex.java (main class)
import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author Pritom K Mondal * @version 1.0 */ public class StringRegex { public static void main(String[] args) { String regex = "[a-z][a-z0-9]{8,10}@[a-z0-9]{5,9}.com"; StringRegex.stringFromRegex(regex); regex = "[\\w][\\D]*[\\d\\W]+[abc.][abc09]+"; StringRegex.stringFromRegex(regex); regex = "[A-Z]{4}-#%[\\d]{3}"; StringRegex.stringFromRegex(regex); regex = "www.[a-z][a-z0-9-_]{5,15}[a-z].com"; StringRegex.stringFromRegex(regex); regex = "01[7856][0-9]{2}-[0-9]{6}"; StringRegex.stringFromRegex(regex); } public static void stringFromRegex(String regex) { String regexConverted = cvtLineTerminators(regex); System.out.println("Regex: " + regexConverted); String fullString = ""; fullString = parse(regexConverted, ""); if(fullString.matches(regex)) { System.out.println("Matches: " + regex + ", String: " + fullString + ", Length: " + fullString.length()); } else { System.err.println("Matches Failed: " + regex + ", String: " + fullString + ", :Length: " + fullString.length()); } System.out.println("\n\n"); } private static String parse(String regex, String fullString) { Random random = new Random(); if(regex.trim().length() > 0) { Boolean allow = false, processed = false; if(regex.startsWith("[") && (regex.substring(0, regex.indexOf("]") + 1).matches("(.*)[a-z]\\-[a-z](.*)") || regex.substring(0, regex.indexOf("]") + 1).matches("(.*)[A-Z]\\-[A-Z](.*)") || regex.substring(0, regex.indexOf("]") + 1).matches("(.*)d(.*)") || regex.substring(0, regex.indexOf("]") + 1).matches("(.*)D(.*)") || regex.substring(0, regex.indexOf("]") + 1).matches("(.*)w(.*)") || regex.substring(0, regex.indexOf("]") + 1).matches("(.*)W(.*)") || regex.substring(0, regex.indexOf("]") + 1).matches("\\[([a-z]*)([0-9]*).\\]") || regex.substring(0, regex.indexOf("]") + 1).matches("\\[[A-Z].\\]") || regex.substring(0, regex.indexOf("]") + 1).matches("(.*)[0-9]\\-[0-9](.*)"))) { allow = true; } if(allow) { int start = regex.indexOf("["); int end = regex.indexOf("]", start); String part = regex.substring(start, end + 1); regex = regex.substring(end + 1); int pos1 = 1, pos2 = 1; if(regex.startsWith("{")) { start = 0; String pos = ""; end = regex.indexOf("}", start); pos = regex.substring(start + 1, end); //part = part + regex.substring(start, end + 1); regex = regex.substring(end + 1); if(pos.trim().length() > 0) { if(pos.contains(",")) { String[] poss = pos.split(","); pos1 = Integer.parseInt(poss[0]); pos2 = Integer.parseInt(poss[1]); } else { pos1 = Integer.parseInt(pos); pos2 = Integer.parseInt(pos); } } } //System.out.println("Pos: " + pos1 + " to " + pos2); StringBuilder sb = new StringBuilder(); String str = ""; String printInfo = "Processing-1: " + part; int tried = 0; while(sb.toString().length() == 0 && tried <= 5) { tried++; str = RandomString.nextString(2000); try { Matcher m = Pattern.compile(part).matcher(str); while (m.find()) { sb.append(m.group(0).toString()); } } catch (Exception ex) { System.out.println("Exception: " + ex.getMessage()); } } if(sb.toString().length() > 0) { processed = true; str = sb.toString(); while(true) { if(str.length() < pos2) { str = str.concat(str); } else { break; } } printInfo += " = (" + pos1 + ", " + pos2 + "): "; String cutString = str.substring(0, pos1); if(pos2 - pos1 > 0) { pos2 = random.nextInt(pos2 - pos1); cutString += str.substring(pos1, pos2 + pos1); } printInfo += cutString; //System.out.println(printInfo); fullString += cutString; } else { regex = part + regex; } } if(regex.startsWith("[") && !processed) { processed = true; int start = regex.indexOf("["); int end = regex.indexOf("]", start); String part = regex.substring(start + 1, end); regex = regex.substring(end + 1); String printInfo = "Processing-2: " + part; int pos1 = 1, pos2 = 1; if(regex.startsWith("{")) { start = 0; String pos = ""; end = regex.indexOf("}", start); pos = regex.substring(start + 1, end); regex = regex.substring(end + 1); if(pos.trim().length() > 0) { if(pos.contains(",")) { String[] poss = pos.split(","); pos1 = Integer.parseInt(poss[0]); pos2 = Integer.parseInt(poss[1]); } else { pos1 = Integer.parseInt(pos); pos2 = Integer.parseInt(pos); } } } String pushString = ""; for(int i = 0; i < pos1; i++) { pushString += part; } if(pos2 - pos1 > 0) { pos2 = random.nextInt(pos2 - pos1); for(int i = 0; i < pos2; i++) { pushString += part; } } printInfo += "{" + pos1 + "," + pos2 + "} = " + pushString; //System.out.println(printInfo); fullString += pushString; } if(!processed) { //System.out.println("Handled: " + regex); regex = "[" + regex; int fa = regex.indexOf("]"), f2 = regex.indexOf("{"), f3 = regex.indexOf("[", 1); if(fa > f3) fa = f3; if(fa > f2) fa = f2; if(fa < 0) { if(f2 < f3 && f2 >= 0) { fa = f2; } else if(f3 > f2 && f3 >= 0) { fa = f3; } else { fa = regex.length(); } } //regex = regex.substring(0, fa) + "]" + regex.substring(fa); regex = regex.substring(0, 2) + "]" + regex.substring(2); //System.out.println("Handled: " + regex); } fullString = parse(regex, fullString); } return fullString; } private static String cvtLineTerminators (String s) { s = s.replaceAll("\\*", "{0,10}"); s = s.replaceAll("\\+", "{1,10}"); StringBuffer sb = new StringBuffer (); int oldindex = 0, newindex; while ((newindex = s.indexOf ("\\n", oldindex)) != -1) { sb.append (s.substring (oldindex, newindex)); oldindex = newindex + 2; sb.append ('\n'); } sb.append (s.substring (oldindex)); s = sb.toString (); sb = new StringBuffer (); oldindex = 0; while ((newindex = s.indexOf ("\\r", oldindex)) != -1) { sb.append (s.substring (oldindex, newindex)); oldindex = newindex + 2; sb.append ('\r'); } sb.append (s.substring (oldindex)); s = sb.toString (); sb = new StringBuffer (); oldindex = 0; while ((newindex = s.indexOf ("\\s", oldindex)) != -1) { sb.append (s.substring (oldindex, newindex)); oldindex = newindex + 2; sb.append (" "); } sb.append (s.substring (oldindex)); return sb.toString(); } }
RandomString.java
import java.util.Random; /** * * @author Pritom K Mondal */ public class RandomString { private static final char[] symbols = new char[10 + 26 + 26 + 3 + 8]; private static final char[] chars = new char[52]; private static final char[] numbers = new char[10]; static { for (int idx = 0; idx < 10; ++idx) { numbers[idx] = (char) ('0' + idx); } for (int idx = 10; idx < 36; ++idx) { chars[idx - 10] = (char) ('a' + idx - 10); } for (int idx = 36; idx < 62; ++idx) { chars[idx - 10] = (char) ('A' + idx - 36); } /** * String */ int total = 0; for(int idx = 48; idx <= 57; idx++, total++) { symbols[total] = (char) idx; }// 10 (10) for(int idx = 65; idx <= 90; idx++, total++) { symbols[total] = (char) idx; } // 26 (36) for(int idx = 97; idx <= 122; idx++, total++) { symbols[total] = (char) idx; } // 26 (62) for(int idx = 44; idx <= 46; idx++, total++) { symbols[total] = (char) idx; } // 3 (65) int[] copyFrom = { 64, 95, 44, 46, 45, 145, 146, 35 }; //@ _ , . - ‘ ’ # for(int idx = 0; idx < copyFrom.length; idx++, total++) { symbols[total] = (char) copyFrom[idx]; } // 8 (73) //System.out.println(total); } private static Random random = new Random(); private static char[] buf; public static String fullString() { return new String(symbols); } public static String nextString(int length) { if (length < 1) { throw new IllegalArgumentException("length < 1: " + length); } buf = new char[length]; //System.out.println(symbols); for (int idx = 0; idx < buf.length; ++idx) { buf[idx] = symbols[random.nextInt(symbols.length)]; } return new String(buf); } public static String nextNumber(int length) { if (length < 1) { throw new IllegalArgumentException("length < 1: " + length); } buf = new char[length]; for (int idx = 0; idx < buf.length; ++idx) { buf[idx] = numbers[random.nextInt(numbers.length)]; } return new String(buf); } public static String nextCharacter(int length) { if (length < 1) { throw new IllegalArgumentException("length < 1: " + length); } buf = new char[length]; for (int idx = 0; idx < buf.length; ++idx) { buf[idx] = chars[random.nextInt(chars.length)]; } return new String(buf); } }
Subscribe to:
Posts (Atom)