Regular Expressions 101

Save & Share

Flavor

  • PCRE2 (PHP >=7.3)
  • PCRE (PHP <7.3)
  • ECMAScript (JavaScript)
  • Python
  • Golang
  • Java 8
  • .NET 7.0 (C#)
  • Rust
  • Regex Flavor Guide

Function

  • Match
  • Substitution
  • List
  • Unit Tests

Tools

Sponsors
There are currently no sponsors. Become a sponsor today!
An explanation of your regex will be automatically generated as you type.
Detailed match information will be displayed here automatically.
  • All Tokens
  • Common Tokens
  • General Tokens
  • Anchors
  • Meta Sequences
  • Quantifiers
  • Group Constructs
  • Character Classes
  • Flags/Modifiers
  • Substitution
  • A single character of: a, b or c
    [abc]
  • A character except: a, b or c
    [^abc]
  • A character in the range: a-z
    [a-z]
  • A character not in the range: a-z
    [^a-z]
  • A character in the range: a-z or A-Z
    [a-zA-Z]
  • Any single character
    .
  • Alternate - match either a or b
    a|b
  • Any whitespace character
    \s
  • Any non-whitespace character
    \S
  • Any digit
    \d
  • Any non-digit
    \D
  • Any word character
    \w
  • Any non-word character
    \W
  • Non-capturing group
    (?:...)
  • Capturing group
    (...)
  • Zero or one of a
    a?
  • Zero or more of a
    a*
  • One or more of a
    a+
  • Exactly 3 of a
    a{3}
  • 3 or more of a
    a{3,}
  • Between 3 and 6 of a
    a{3,6}
  • Start of string
    ^
  • End of string
    $
  • A word boundary
    \b
  • Non-word boundary
    \B

Regular Expression
No Match

/
/
gm

Test String

Code Generator

Generated Code

# coding=utf8 # the above tag defines encoding for this document and is for Python 2.x compatibility import re regex = r"((((\b(#|\w)+\b\.)?(\bprototype\b\.)?(\b(#|\w)+\b)(\s*\=\s*)?)?(\b(#|\w)+\b\s*)\([\s\w,=]*\s*\))|(\bclass\b\s+\b\w+\b\s*(extends\s*\b\w+\b))(?=\s*\{[\s\S]+\}))(?=\s*\{[\s\S]+\})" test_str = ("/**\n" " * Created by jetbrains web development IDE ( Web/PhpStorm ).\n" " * Project: web-component - spineNav\n" " * User: Pascal Gaudin\n" " * Mail: pascal.gaudin@zimmerbiomet.com\n" " * Date: 14/01/2023\n" " * Time: 14:00\n" " */\n\n\n\n\n" "/**\n" " *\n" " * @type {Window.HTMLElementExtd}\n" " */\n" "window.HTMLElementExtd = class HTMLElementExtd extends HTMLElement {\n" " shadowRoot;\n" " style;\n" " elementCustomName;\n" " /**\n" " *\n" " * @param props\n" " */\n" " constructor(props) {\n" " super(props);\n" " this.shadowRoot = this.attachShadow({mode: 'open'});\n" " this.host=this.shadowRoot.host;\n" " this.style= document.createElement('style');\n" " this.elementCustomName = this.host.tagName.toLowerCase()\n" " let css = Tools.fetchSync(`web-component/${this.elementCustomName}/default.css`);\n" " const iJson=new Css(css)\n" " const jsonCss= iJson.toJson();\n" " console.log('logg : ', jsonCss);\n\n" " css += Tools.fetchSync(`web-component/${this.elementCustomName}/custom-element.css`);\n\n" " this.style.textContent = css;\n" " this.shadowRoot.appendChild(this.style);\n" " }\n\n" " /**\n" " *\n" " * @param objVar\n" " */\n" " setVarInCtx(objVar){\n" " for(name in objVar ) this[name] = objVar[name];\n\n" " }\n\n" " /**\n" " *\n" " * @param className\n" " * @returns {string}\n" " */\n" " getStyle(className) {\n" " var cssText = \"\";\n" " var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;\n" " for (var x = 0; x < classes.length; x++) {\n" " if (classes[x].selectorText == className) {\n" " cssText += classes[x].cssText || classes[x].style.cssText;\n" " }\n" " }\n" " return cssText;\n" " }\n\n" " /**\n" " *\n" " * @returns {boolean}\n" " */\n" " get firstTime(){\n" " return this.host.ownerDocument.getElementsByTagName(this.elementCustomName).length===1;\n" " }\n\n" " /**\n" " *\n" " * @returns {*[]}\n" " */\n" " static get observedAttributes() {\n" " return [];\n" " }\n" " /**\n" " * document.adoptNode(el)\n" " */\n" " adoptedCallback()\n" " {\n" " console.log(`Custom-Element ${this.host.nodeName.toLowerCase()} adopt Node !`);\n" " }\n\n" " /**\n" " * each el.setAttribute\n" " *\n" " * @param attrName\n" " * @param oldVal\n" " * @param newVal\n" " */\n" " attributeChangedCallback(attrName, oldVal, newVal){\n" " console.log(`Custom-Element ${this.host.nodeName.toLowerCase()} attribute '${attrName}' Changed with value '${newVal}' !`);\n\n" " }\n\n" " /**\n" " * el.remove()\n" " *\n" " */\n" " disconnectedCallback(){\n" " console.log(`Custom-Element ${this.host.nodeName.toLowerCase()} Element remove !` );\n" " }\n\n" " /**\n" " *\n" " */\n" " connectedCallback(){\n" " console.log(`Custom-Element ${this.host.nodeName.toLowerCase()} was inserted in DOM!`);\n\n" " }\n" "}\n\n\n" "/**\n" " * Created by jetbrains WebStorm .\n" " * Project: web-component - MyProject\n" " * User: Pascal Gaudin\n" " * Mail:\n" " * Date: 23/01/2023\n" " * Time: 10:58\n" " */\n\n\n" "/**\n" " *\n" " * @param attributes\n" " */\n" "HTMLElement.prototype.setAttributes=function (attributes) {\n" " for (const name in attributes) {\n" " if(name=='textContent') this.textContent= attributes[name];\n" " if(attributes[name]&&attributes[name]!=='')this.setAttribute(name,attributes[name]);\n" " if( attributes[name]==='')this.setAttribute(name,'');\n" " }\n" "}\n" "/**\n" " *\n" " * @returns {*[]}\n" " */\n" "document.createElements =function (){\n" " const args= [];\n" " [...arguments].forEach((arg)=>{\n" " args.push(document.createElement(arg));\n" " })\n" " return args;\n" "}\n\n" "/**\n" " *\n" " */\n" "document.toggleFullScreen=function() {\n" " if (!document.fullscreenElement) {\n" " document.documentElement.requestFullscreen();\n" " } else {\n" " if (document.exitFullscreen) {\n" " document.exitFullscreen();\n" " }\n" " }\n" "}\n" "/**\n" " *\n" " * @returns {*[]}\n" " */\n" "HTMLElement.prototype.appendChilds =function ( ) {\n" " const args= [];\n" " [...arguments].forEach((arg)=>{\n" " args.push(this.appendChild(arg));\n" " })\n" " return args;\n" "}\n" "/**\n" " *\n" " * @type {function(): *[]}\n" " */\n" "ShadowRoot.prototype.appendChilds= HTMLElement.prototype.appendChilds ;\n\n" "/**\n" " *\n" " * @returns {*[]}\n" " */\n" "HTMLElement.prototype.removeChilds=function( ){\n" " const args= [];\n" " [...arguments].forEach((arg)=>{\n" " args.push(this.removeChild(arg));\n" " })\n" " return args;\n" "}\n" "/**\n" " *\n" " * @param txt\n" " */\n" "HTMLInputElement.prototype.setFocusBack =function( txt){\n\n" "}\n\n" "/**\n" " *\n" " * @param kill\n" " */\n" "HTMLElement.prototype.disconnect=function(kill){\n" " const numObserved = this.dataset.observed;\n" " const infoElmt=`of the element '${this.tagName.toLowerCase()}' (with name:'${this.getAttribute('name')??''}')`\n" " if(this.dataset.hasObserverConnected && this.observer[numObserved] ) {\n" " this.observer[numObserved].disconnect();\n" " console.log( `The observer ${infoElmt} n° ${ numObserved } has been disconnected.`);\n" " if(kill) {\n" " delete this.observer[numObserved] ;\n" " console.log( `The observer ${infoElmt} n° ${ numObserved } has been destroy.`);\n" " }\n" " delete this.dataset.hasObserverConnected;\n" " } else {\n" " console.log( `The observer ${infoElmt} is not connected.`)\n" " };\n\n" "}\n\n" "/**\n" " *\n" " * @param type\n" " * @param oldValue\n" " * @param subtree\n" " * @param log\n" " */\n" "HTMLElement.prototype.observe =function( type,oldValue=true, subtree=true,log=true){\n" " let numObserved=this.dataset.observed;\n" " const infoElmt=`of the element '${this.tagName.toLowerCase()}' (with name:'${this.getAttribute('name')??''}')`\n" " if(arguments && !numObserved) {\n" " this.config = {...type, subtree};//attributeFilter\n" " const callback = {}, propertieAllowed = {};\n" " ['childList', 'attributes', 'characterData'].forEach(_type => {\n" " this.config[_type] = type.hasOwnProperty(_type);\n" " callback[_type] = type[_type] ?? undefined;\n\n\n" " })\n" " if (this.config.attributes) this.config.attributeOldValue = oldValue;\n" " if (this.config.characterData) this.config.characterDataOldValue = oldValue;\n\n" " propertieAllowed.attributes = ((mut) => { //attributes target newValue attributeName oldValue\n" " return {\n" " target : mut.target, newValue: mut.target.getAttribute(mut.attributeName),\n" " attributeName: mut.attributeName, oldValue: mut.oldValue\n" " }\n" " });\n" " propertieAllowed.childList = ((mut) => {//childList : target addedNodes removedNodes\n" " return {target: mut.target, addedNodes: [...mut.addedNodes], removedNodes: [...mut.removedNodes]}\n" " });\n" " propertieAllowed.characterData = ((mut) => { //characterData oldText newText target\n" " return {oldText: mut.oldValue, newText: mut.target.data, target: mut.target}\n" " });\n\n" " const cbk = (mutationsList) => {\n" " for (var mutation of mutationsList) {\n" " if (callback[mutation.type]) callback[mutation.type].call(this, propertieAllowed[mutation.type](mutation));\n" " }\n" " }\n" " numObserved= 'obs-'+new Date().getTime();\n" " this.dataset.observed=numObserved;\n\n" " this.observer={[numObserved] : new MutationObserver(cbk)};\n" " if(log)console.log( `The observer ${infoElmt} n° ${ numObserved } is now created.`)\n" " }\n" " this.observer[numObserved].observe(this, this.config);\n" " this.dataset.hasObserverConnected= true;\n" " if(log)console.log( `The observer ${infoElmt} n° ${ numObserved } is connected.\\n\\n`)\n\n" "}\n\n\n" "/**\n" " *\n" " * @param regexs\n" " * @param strs\n" " * @param callbacs\n" " */\n" "String.prototype.replaceWithArray=function ( regexs, strs,callbacs) {\n" " let str=this;\n" " regexs.forEach((regex,idx)=>{\n" " str = String.prototype.replace.call(str,regex,strs.at(idx),callbacs?.at(idx));\n" " });\n" " return str;\n" "}\n") matches = re.finditer(regex, test_str, re.MULTILINE) for matchNum, match in enumerate(matches, start=1): print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group())) for groupNum in range(0, len(match.groups())): groupNum = groupNum + 1 print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum))) # Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html