Regular Expressions in PHP, MySQL by programmerblog.netProgrammer Blog
This PPT explains, how to use regular expressions in PHP. PHP has two types of regular expressions Perl Style and Posix Style.
Read detailed tutorials on http://programmerblog.net
Regular Expressions in PHP, MySQL by programmerblog.netProgrammer Blog
This PPT explains, how to use regular expressions in PHP. PHP has two types of regular expressions Perl Style and Posix Style.
Read detailed tutorials on http://programmerblog.net
sed, known as the “streams editor”, is a powerful tool for text manipulation on UNIX systems. Unlike vim, sed can operate on files of limitless size. The session will cover some of the intermediate concepts such as grouping and back referencing, regular expressions, replacing the nth occurrence of a pattern, operation on every nth line and so on. We will spice up the session with a few “sed one-liners/idioms”
Oracle database supports perl- and POSIX-compatible regular expressions with five elegant and powerful functions: REGEXP_REPLACE, REGEXP_SUBSTR, REGEXP_INSTR, REGEXP_LIKE, and REGEXP_COUNT.
This session will demonstrate their nuances and how to use them effectively for data cleansing, manipulation and selection, for validating things such as Social Security Numbers, credit cards, IP addresses, phone numbers, DNAs, XMLs, for extracting things such as email-ids, hostnames from URLs and strings, and for transposing delimited columns to rows. There will be a demo of a few tricky examples taken from forums.oracle.com and asktom.oracle.com.
The session will end with fuzzy matching and optimization techniques, and things to watch out for.
http://docs.oracle.com/cd/E11882_01/appdev.112/e25518/adfns_regexp.htm
From my November 3, 2011 talk at MNPHP. Regular expressions are a powerful tool available in nearly every programming language or platform, including PHP. I go over the history of POSIX vs. PCRE, examples in PHP, and optimizations on how to write faster expressions.
Regular Expressions: every developer's best friend and worst nightmare! Join Andrei Zmievski, PHP developer and author of the PHP Regex (PCRE) extension, on a journey that will take you from your first steps into the world of regular expressions to the mastery of this most useful of tools. A must for everyone who's ever wondered what /(?=\d+)bar/ means.
sed, known as the “streams editor”, is a powerful tool for text manipulation on UNIX systems. Unlike vim, sed can operate on files of limitless size. The session will cover some of the intermediate concepts such as grouping and back referencing, regular expressions, replacing the nth occurrence of a pattern, operation on every nth line and so on. We will spice up the session with a few “sed one-liners/idioms”
Oracle database supports perl- and POSIX-compatible regular expressions with five elegant and powerful functions: REGEXP_REPLACE, REGEXP_SUBSTR, REGEXP_INSTR, REGEXP_LIKE, and REGEXP_COUNT.
This session will demonstrate their nuances and how to use them effectively for data cleansing, manipulation and selection, for validating things such as Social Security Numbers, credit cards, IP addresses, phone numbers, DNAs, XMLs, for extracting things such as email-ids, hostnames from URLs and strings, and for transposing delimited columns to rows. There will be a demo of a few tricky examples taken from forums.oracle.com and asktom.oracle.com.
The session will end with fuzzy matching and optimization techniques, and things to watch out for.
http://docs.oracle.com/cd/E11882_01/appdev.112/e25518/adfns_regexp.htm
From my November 3, 2011 talk at MNPHP. Regular expressions are a powerful tool available in nearly every programming language or platform, including PHP. I go over the history of POSIX vs. PCRE, examples in PHP, and optimizations on how to write faster expressions.
Regular Expressions: every developer's best friend and worst nightmare! Join Andrei Zmievski, PHP developer and author of the PHP Regex (PCRE) extension, on a journey that will take you from your first steps into the world of regular expressions to the mastery of this most useful of tools. A must for everyone who's ever wondered what /(?=\d+)bar/ means.
Digital Marketing: Current Trends in iGamingNicky Senyard
Nicky Senyard, the founder and CEO of the Income Access Group, discussed 2015 trends in online gaming and digital marketing in a presentation at the ICE Totally Gaming conference in London, England, on 1st Feb. 2015. This slide-share accompanied Nicky's speech.
Hvad gør Vegas’s dufte så enestående?
✔ En ekstra høj andel af parfumeolie på 12% - 17%
✔ Duftens holdbarhed på huden holder længere
✔ Eksklusive dufte – 62 forskellige dufte i sortimentet
✔ Et meget attraktivt forhold mellem pris og ydelse
✔ Tysk Top kvalitet
✔ Farve Gravering på flakon, æske, hel bagside med Tekst/billeder
El Maestro Sri Deva Fenix nos presenta Un instante Mágico, donde la Ciencia, el Arte y la Magia se dan cita en una elaborada Alquimia Natural…
Magnificas imágenes que suspenden una fracción del tiempo y nos invitan a reflexionar sobre nuestra interacción con nuestro entorno y como podemos afectarlo positiva o negativamente...
Have you been scared off by Klingon-looking one-liners in Perl? Do you resort to writing complicated recursive functions just to parse some HTML? Don't!
I'll demystify regular expressions and show you how best to do them in PHP. We'll cover the syntax and functions that make PHP a great text-parsing language, and give you the foundation to learn more.
As a bonus, I'll give you two cases people often use as examples for regexes that PHP gives you better native ways to accomplish.
Do you have data and lists you keep having to massage to make it useful for your project? Have you heard of regular expressions but been frightened by the Klingon-looking examples? Fear no longer!
I’ll demystify regular expressions and show you how best to do them in PHP. We’ll cover the syntax and functions that make PHP a great text-parsing language, and give you the foundation to learn more.
As a bonus, I’ll give you two cases people often use as examples for regexes that PHP gives you better native ways to accomplish.
Don't Fear the Regex - Northeast PHP 2015Sandy Smith
Have you been scared off by Klingon-looking one-liners in Perl? Do you resort to writing complicated recursive functions just to parse some HTML? Don’t!
I’ll demystify regular expressions and show you how best to do them in PHP. We’ll cover the syntax and functions that make PHP a great text-parsing language, and give you the foundation to learn more.
As a bonus, I’ll give you two cases people often use as examples for regexes that PHP gives you better native ways to accomplish.
Don't Fear the Regex - CapitalCamp/GovDays 2014Sandy Smith
Have you been scared off by Klingon-looking one-liners in Perl? Do you resort to writing complicated recursive functions just to parse some HTML? Don't!
I'll demystify regular expressions and show you how best to do them in PHP. We'll cover the syntax and functions that make PHP a great text-parsing language, and give you the foundation to learn more.
As a bonus, I'll give you two cases people often use as examples for regexes that PHP gives you better native ways to accomplish.
Given at CapitalCamp & GovDays 2014
PT.BUZOO INDONESIA is No1 Japanese offshore development company in Indonesia.
We are professional of web solution and smartphone apps. We can support Japanese, English and Indonesia.
We are hiring now at http://buzoo.co.id/
Regular expressions are the main way many tools matches patterns within strings.
For example, finding pieces of text within a larger doc, or finding a restriction site within a larger sequence. This slide report illustrates what a RegEx is and what you can do to find, match, compare or replace text of documents or code.
In the last sessions we have seen that P4D (Python 4 Delphi) is powerful enough to offer components, Python packages or libraries in Delphi or Lazarus (FPC). This time we go the other way of usage and integration; how does the Python or web world in the shell benefit from the VCL components as GUI controls. We create a Python extension module from Delphi classes, packages or functions. Building Delphi’s VCL library as a specific Python module in a console or editor and launching a complete Windows GUI from a script can be the start of a long journey.
The flood of Open APIs is now so blatant that we take a closer look at some basics and principles. Of course, the best way to understand how APIs work is to try them. While most APIs require access via API keys or have complicated authentication and authorization methods, there are also open APIs with no requirements or licenses whatsoever. This is especially useful for beginners as we can start exploring different APIs right away. It’s also useful for web developers who want easy access to a sample dataset for their app; e.g. most weather apps get their weather forecast data from a weather API instead of building weather stations themselves.
Faker is a Python library that generates fake data. Fake data is often used for testing or filling databases with some dummy data. Faker is heavily inspired by PHP's Faker, Perl's Data::Faker, and by Ruby's Faker.
Many of the applications and organizations provide avatar features. Finally, synthetic datasets can minimize privacy concerns. Attempts to anonymize data can be ineffective, as even if sensitive/identifying variables are removed from the dataset
Python for Delphi (P4D) is a set of free components that wrap up the Python DLL into Delphi and Lazarus (FPC). They let you easily execute Python scripts, create new Python modules and new Python types. You can create Python extensions as DLLs and much more like scripting. P4D provides different levels of functionality: Low-level access to the python API High-level bi-directional interaction with Python Access to Python objects using Delphi custom variants (VarPyth.pas).
Python for Delphi (P4D) is a set of free components that wrap up the Python DLL into Delphi and Lazarus (FPC). They let you easily execute Python scripts, create new Python modules and new Python types. You can create Python extensions as DLLs and much more like scripting. P4D provides different levels of functionality:
Low-level access to the python API
High-level bi-directional interaction with Python
Access to Python objects using Delphi custom variants (VarPyth.pas)
Wrapping of Delphi objects for use in python scripts using RTTI (WrapDelphi.pas)
Creating python extension modules with Delphi classes and functions
Generate Scripts in maXbox from Python Installation
With the following report I show how to host and execute a deep learning project on a cloud. The cloud is hosted by google Colab and enables working and testing in teams. Lazarus and FreePascal is also being built in colab and the deep learning network is compiled and trained too in a Jupyter notebook with Python scripts.
The portable pixmap format(PPM), the portable graymap format(PGM) and portable bitmap format(PBM) are image file formats designed to be easily exchanged between platforms. They are also sometimes referred collectively as the portable anymap format(PNM). These formats are a convenient (simple) method of saving image data. And the format is not even limited to graphics, its definition allowing it to be used for arbitrary three-dimensional matrices or cubes of unsigned integers.
This tutor puts a trip to the kingdom of object recognition with computer vision knowledge and an image classifier.
Object detection has been witnessing a rapid revolutionary change in some fields of computer vision. Its involvement in the combination of object classification
as well as object recognition makes it one of the most challenging topics in the domain of machine learning & vision.
How can we visualize data in machine learning with VS Code? This is a C# wrapper for the GraphViz graph generator for dotnet core. Further bindings for Python GraphViz are shown and exports to MS Power BI all in MS Visual Code, Jupyter and dotnet core.
K-CAI NEURAL API is a Keras based neural network API for machine learning that will allow you to prototype with a lots of possibilities of Tensorflow! Python, Free Pascal and Delphi together in Google Colab, Git or the Community Edition.
Software is changing the world. CGC is a Common Gateway Coding as the name says, it is a "common" language approach for almost everything. I want to show how a multi-language approach to infrastructure as code using general purpose programming languages lets cloud engineers and code producers unlocking the same software engineering techniques commonly used for applications.
Code Review Checklist: How far is a code review going? "Metrics measure the design of code after it has been written, a Review proofs it and Refactoring improves code."
In this paper a document structure is shown and tips for a code review.
Some checks fits with your existing tools and simply raises a hand when the quality or security of your codebase is impaired.
Open LDAP as A directory serviceis a system for storing and retrieving information in a tree-like structure with the following key properties:
Optimized for reading Distributed storage model Extensible data storage types Advanced search capabilities Consistent replication possibilities
They are a block of code plus the bindings to the environment they came from (RagusaIdiom).
Closures are reusable blocks of code that capture the environment and can be passed around as method arguments for immediate or deferred execution.
This tutor explains a solution to attach a console to your app. Basically we want an app to have two modes, a GUI mode and a non-GUI mode for any humans and robots. A NoGUI app provides a mechanism for storage and retrieval of data and functions in means other than the normal GUI used in operating systems.
Introduction to use machine learning in python and pascal to do such a thing like train prime numbers when there are algorithms in place to determine prime numbers. See a dataframe, feature extracting and a few plots to re-search for another hot experiment to predict prime numbers.
This tutor shows the train and test set split with binary classifying, clustering and 3D plots and discuss a probability density function in scikit-learn on synthetic datasets. The dataset is very simple as a reference of understanding.
This tutor shows the train and test set split with histogram and a probability density function in scikit-learn on synthetic datasets. The dataset is very simple as a reference of understanding.
In this article you will learn hot to use tensorflow Softmax Classifier estimator to classify MNIST dataset in one script.
This paper introduces also the basic idea of a artificial neural network.
The term “machine learning” is used to describe one kind of “artificial intelligence” (AI) where a machine is able to learn and adapt through its own experience. We crawled and collected 30 top overview diagrams which shows the topic of methods, algorithms and concepts.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Maxbox starter20
1. maXbox Starter 20
Start with Regular Expressions
1.1 From TRex to RegEx
Regular expressions are the main way many tools matches’ patterns within strings. For example,
finding pieces of text within a larger document, or finding a restriction site within a larger
sequence. This tutorial illustrates what a RegEx is and what you can do to find, match, compare
or replace text of documents or code.
As you will see Regular expressions are composed of characters, character classes,
metacharacters, quantifiers, and assertions. Hope you did already read Starters 1 till 19 at:
http://sourceforge.net/apps/mediawiki/maxbox/
What’s a Regular Expression?
A regular expression (RegEx): describes a search pattern of text typically made up from special
characters called metacharacters:
• You can test whether a string matches the expression pattern
• You can use a RegEx to search/replace characters in a string
• It’s very powerful, but tough to read
Regular expressions occur in many places and masks, not alone in code or languages
environments:
Text editors, shells or search tools like Grep1 allow also RegEx in search/replace functions, like
the following screen-shot figure out.
1: Find with RegEx
Let’s jump to history and the beginning of RegEx with Perl. Perl was a horribly flawed and very
useful scripting language, based on UNIX shell scripting and C, that helped lead to many other
1
Global Regular Expression Print / Parser
2. better languages. Perl was and is also excellent for string/file/text processing because it built
regular expressions directly into the language as a first-class data type.
Many command-line shell Linux/Mac tools (ed, vi, grep, egrep, sed, awk) support Regular
Expressions, for e.g. Grep:
grep -e "[pP]hone.*206[0-9]{7}" contacts.txt
>> phone { 206-685-2181}
Grep is a tool that originated from the UNIX world during the 1970's. It can search through files
and folders (directories in UNIX) and check which lines in those files match a given regular
expression. Grep will output the filenames and the line numbers or the actual lines that matched
the regular expression.
1.2 RegEx out of the Box
As you already know the tool is split up into the toolbar across the top, the editor or code part in
the centre and the output window at the bottom or the interface part on the right. Change that in
the menu /View at our own style.
In maXbox you will execute the RegEx as a script, libraries and units are already built.
Before this starter code will work you will need to download maXbox from the website. It can
be down-loaded from http://www.softwareschule.ch/maxbox.htm (you’ll find the download
maxbox3.zip on the top left of the page). Once the download has finished, unzip the file, making
sure that you preserve the folder structure as it is. If you double-click maxbox3.exe the box
opens a default demo program. Test it with F9 / F2 or press Compile and you should hear a
sound. So far so good now we’ll open the example:
309_regex_powertester2.txt
If you can’t find the two files try also the zip-file (48100 bytes) loaded from:
http://www.softwareschule.ch/examples/309_regex_powertester2.txt
Now let’s take a look at the code of this fist part project. Our first line is
01 program RegEx_Power_Tester_TRex;
We name it, means the program’s name is above.
This example requires two objects from the classes: TRegExpr and TPerlRegEx of
PerlRegEx so the second one is from the well known PCRE Lib.
TPerlRegEx is a Delphi VCL wrapper around the open source PCRE library, which implements
Perl-Compatible Regular Expressions.
This version of TPerlRegEx is compatible with the TPerlRegEx class (PCRE 7.9) in the
RegularExpressionsCore unit in Delphi XE. In fact, the unit in Delphi XE and maXbox3 is
derived from the version of TPerlRegEx that we are using now.
Let’s do a first RegEx now. We want to check if a name is a valid Pascal name like a syntax
checker does. We use straight forward a function in the box:
732 if ExecRegExpr('^[a-zA-Z_][a-zA-Z0-9_].*','pascal_name_kon')
then writeln('pascal name valid') else writeln('pascal name invalid');
This is a useful global function:
function ExecRegExpr (const ARegExpr, AInputStr: string): boolean;
2
3. It is true if a string AInputString matches regular expression ARegExpr and it will raise an
exception if syntax errors in ARegExpr are done.
Now let’s analyse our first RegEx step by step '^[a-zA-Z_][a-zA-Z0-9_].*':
^ matches the beginning of a line; $ the end
[a-z] matches all twenty six small characters from 'a' to 'z'
[a-zA-Z_] matches any letter with underscore
[a-zA-Z0-9_] matches any letter or digit with underscore
.* (a dot) matches any character except n
.* * means 0 or more occurrences
[ ] group characters into a character set;
A lot of rules for the beginning, and they look ugly for novices, but really they are very simple
(well, usually simple ;)), handy and powerful tool too. You can validate e-mail addresses; extract
phone numbers or ZIP codes from web-pages or documents, search for complex patterns in log
files and all you can imagine! Rules (templates) can be changed without your program
recompilation! This can be especially useful for user input validation in DBMS and web projects.
Try the next one:
if ExecRegExpr('M[ae][iy]e?r.*[be]', 'Mairhuberu')
then writeln('regex maierhuber true') else writeln('regex maierhuber false');
? Means 0 or 1 occurrences
Any item of a regular expression may be followed by another type of metacharacters – called
iterators. Using this characters you can specify number of occurrences of previous characters so
inside [], most modifier keys act as normal characters:
/what[.!*?]*/ matches "what", "what.", "what!", "what?**!", ..
So a character class is a way of matching 1 character in the string being searched to any of a
number of characters in the search pattern.
Character classes are defined using square brackets. Thus [135] matches any of 1, 3, or 5. A
range of characters (based on ASCII order) can be used in a character class: [0-7] matches any
digit between 0 and 7, and [a-z] matches and small (but not capital) letter.
Note that the hyphen is being used as a metacharacter here. To match a literal hyphen in a
character class, it needs to be the first character. So [-135] matches any of -, 1, 3, or 5. [-0-9]
matches any digit or the hyphen.
What if we want to define a certain place? An assertion is a statement about the position of the
match pattern within a string. The most common assertions are “^”, which signifies the beginning
of a string, and “$”, which signifies the end of the string.
For example search all empty or blank lines: Search empty lines: ‘^$’
This is how we can assert a valid port number with ^ and $:
745 if ExecRegExpr('^(:dd?d?d?d?)$',':80009')
then writeln('regex port true') else writeln('regex port false');
There are 3 main operators that use regular expressions:
1. Matching (which returns TRUE if a match is found and FALSE if no match is found.
2. Substitution, which substitutes one pattern of characters for another within a string
3. Split, which separates a string into a series of substrings
3
4. If you want to match a certain number of repeats of a group of characters, you can group the
characters within parentheses. For example, /(cat){3}/ matches 3 reps of “cat” in a row:
“catcatcat”. However, /cat{3}/ matches “ca” followed by 3 t’s: “cattt”.
And things go on. To negate or reject a character class, that is, to match any character EXCEPT
what is in the class, use the caret ^ as the first symbol in the class. [^0-9] matches any
character that isn’t a digit. [^-0-9] ,matches any character that isn’t a hyphen or a digit.
Now its time to reflect:
RE Metacharacter Matches…
^ beginning of line
$ end of line
char Escape the meaning of char following it
[^] One character not in the set
< Beginning of word anchor
> End of word anchor
( ) or ( ) Tags matched characters to be used later (max = 9)
| or | Or grouping
x{m} Repetition of character x, m times (x,m = integer)
x{m,} Repetition of character x, at least m times
x{m,n} Repetition of character x between m and m times
2. Overview of Matches
You can specify a series of alternatives for a pattern using "|'' to separate them, so that fee|fie|foe
will match any of "fee'', "fie'', or "foe'' in the target string (as would f(e|i|o)e). The first alternative
includes everything from the last pattern delimiter ("('', "['', or the beginning of the pattern)
up to the first "|'', and the last alternative contains everything from the last "|'' to the next pattern
delimiter.
For this reason, it's common practice to include alternatives in parentheses, to minimize
confusion about where they start and end.
Next a few examples to see the atoms:
rex:= '(no)+.*'; //Print all lines containing one or more consecutive
occurrences of the pattern “no”.
rex:= '.*S(h|u).*'; //Print all lines containing the uppercase letter “S”,
followed by either “h” or “u”.
rex:= '.*.[^0][^0].*'; //Print all lines ending with a period and exactly two
non-zero numbers.
4
5. rex:= '.*[0-9]{6}..*'; //all lines at least 6 consecutive numbers follow by a
period.
Next we want to see how the objects in the box work:
The static versions of the methods are provided for convenience, and should only be used for one
off matches, if you are matching in a loop or repeating the same search often then you should
create an 'instance' of the TRegEx record and use the non static methods.
The RegEx unit defines TRegEx and TMatch as records. That way you don’t have to explicitly
create and destroy them. Internally, TRegEx uses TPerlRegEx to do the heavy lifting.
TPerlRegEx is a class that needs to be created and destroyed like any other class. If you look at
the TRegEx source code, you’ll notice that it uses an interface to destroy the TPerlRegEx
instance when TRegEx goes out of scope. Interfaces are reference counted in Delphi, making
them usable for automatic memory management.
The XE interface to PCRE is a layer of units based on contributions from various people, the
PCRE API header translations in RegularExpressionsAPI.pas
3: The two Classes in compare
Clients are seen in picture 3 as the two classes do the same task. After creating the object RegEx
we set the options:
These are the most important options you can specify:
• preCaseLess Tries to match the regex without paying attention to case. If set,
'Bye' will match 'Bye', 'bye', 'BYE' and even 'byE', 'bYe', etc. Otherwise, only 'Bye'
will be matched. Equivalent to Perl's /i modifier.
• preMultiLine The ^ (beginning of string) and $ (ending of string) regex operaters
will also match right after and right before a newline in the Subject string. This
effectively treats one string with multiple lines as multiple strings. Equivalent to
Perl's /m modifier.
5
6. • preSingleLine Normally, dot (.) matches anything but a newline (n). With
preSingleLine, dot (.) will match anything, including newlines. This allows a
multiline string to be regarded as a single entity. Equivalent to Perl's /s modifier.
• Note that preMultiLine and preSingleLine can be used together.
• preExtended Allow regex to contain extra whitespace, newlines and Perl-style
comments, all of which will be filtered out. This is sometimes called "free-spacing
mode".
• preAnchored Allows the RegEx to match only at the start of the subject or right
after the previous match.
• preUngreedy Repeat operators (?, *, +, {num,num}) are greedy by default, i.e.
they try to match as many characters as possible. Set preUngreedy to use
ungreedy repeat operators by default, i.e. they try to match as few characters as
possible.
Greedy is a strange operator or option. A slight explanation about "greediness".
"Greedy" takes as many as possible; "non-greedy" takes as few as possible. For example, 'b+'
and 'b*' applied to string 'abbbbc' return 'bbbb', 'b+?' returns 'b', 'b*?' returns an empty string,
'b{2,3}?' returns 'bb', 'b{2,3}' returns 'bbb'.
The regular expression engine does “greedy” matching by default!
A typical RegEx client session looks like this:
848 with TPerlRegEx.Create do try //Perl Delphi RegEx
849 RegEx:= '<title>(.+?)</title>';
850 Options:= [preCaseLess];
851 Subject:= 'testa <title> My TRex on Regex</title> testb';
852 If Match then
853 ShowMessageBig(Groups[1]) //SubExpressions[1]) ,MatchedText
854 else
855 ShowMessageBig('Regex Not found');
856 finally
857 Free;
858 end;
Subject is the RegEx and the string on which Match will try to match RegEx. Match attempts to
match the regular expression specified in the RegEx property on the string specified in the
Subject property. If Compile has not yet been called, Match will do so for you.
Call MatchAgain to attempt to match the RegEx on the remainder of the subject string after a
successful call to Match.
Compile: Before it can be used, the regular expression needs to be compiled. Match will call
Compile automatically if you did not do so. If the regular expression will be applied in time-critical
code, you may wish to compile it during your application's initialization. You may also want to call
Study to further optimize the execution of the RegEx.
Let’s have a look at the RegEx itself and the magic behind:
'<title>(.+?)</title>'
What’s about this <title>, it must be a global identifier to find or still exists.
+? one or more ("non-greedy"), similar to {1,}?
It captures everything between the first <title> and the first </title> that follows. This is
usually what you want to do with large sequences in a group.
6
7. Greedy names: Greedy matching can cause problems with the use of quantifiers. Imagine
that you have a long DNA sequence and you try to match /ATG(.*)TAG/. The “.*” matches 0 or
more of any character. Greedy matching causes this to take the entire sequence between the first
ATG and the last TAG. This could be a very long matched sequence.
Note that Regular expressions don’t work very well with nested delimiters or other tree-like
data structures, such as are found in an HTML table or an XML document. We will discuss
alternatives later in a course.
So far we have learned little about RegEx and the past with a TRex eating words as a
book output to us;-). Now it’s time to run your program at first with F9 (if you haven’t
done yet) and learn something about the 309_regex_powertester2.txt with many code
snippets to explore.
One of them is a song finder in the appendix to get a song list from an mp3 file and play them!
4: Mastering
There are plenty more regular expression tricks and operations, which can be found in
Programming Perl, or, for the truly devoted, Mastering Regular Expressions.
Next we enter part two of the insider information about the implementation.
5: Enter a RegEx building
1.3 RegEx in Delphi and maXbox
The TPerlRegEx class aimes at providing any Delphi, Java or C++Builder developer with the
same, powerful regular expression capabilities provided by the Perl programming language
community, created by Larry Wall.
It is implemented as a wrapper around the open source PCRE library.
The regular expression engine in Delphi XE is PCRE (Perl Compatible Regular Expression). It's a
fast and compliant (with generally accepted RegEx syntax) engine which has been around for
7
8. many years. Users of earlier versions of Delphi can use it with TPerlRegEx, a Delphi class
wrapper around it.
TRegEx is a record for convenience with a bunch of methods and static class methods for
matching with regular expressions.
I've always used the RegularExpressionsCore unit rather than the higher level stuff because
the core unit is compatible with the unit that Jan Goyvaerts has provided for free for years. That
was my introduction to regular expressions. So I forgot about the other unit. I guess there's either
a bug or it just doesn't work the way one might expect.
For new code written in Delphi XE, you should definitely use the RegEx unit that is part of Delphi
rather than one of the many 3rd party units that may be available. But if you're dealing with UTF-8
data, use the RegularExpressionsCore unit to avoid needless UTF-8 to UTF-16 to UTF-8
conversions.
The procedure Study procedure Study;
Allows studying the RegEx. Studying takes time, but will make the execution of the RegEx a lot
faster. Call study if you will be using the same RegEx many times. Study will also call Compile
if this had not yet been done.
Depending on what the user entered in Edit1 and Memo1, RegEx might end up being a pretty
complicated regular expression that will be applied to the memo text a great many times. This
makes it worthwhile to spend a little extra time studying the regular expression (later on more).
By the way there’s another tool: Compose and analyze RegEx patterns with RegexBuddy's easy-
to-grasp RegEx blocks and intuitive RegEx tree, instead of or in combination with the traditional
RegEx syntax. Developed by the author of the website http://www.regular-
expressions.info/, RegexBuddy makes learning and using regular expressions easier than
ever.
6: The RegexBuddy and the GUI
Conclusion: A regular expression (RegEx or regexp for short) is a special text string for describing
a search pattern. You can think of regular expressions as wildcards on steroids. You are probably
familiar with wildcard notations such as *.txt to find all text files in a file manager. The RegEx
equivalent is .*.txt$.
8
9. 7: The Secret behind this Regular Expression!?
Study method example:
Depending on what the user entered in Edit1 and Memo1, RegEx might end up being a pretty
complicated regular expression that will be applied to the memo text a great many times. This
makes it worthwhile to spend a little extra time studying the regular expression.
31 with PerlRegEx1 do begin
RegEx:= Edit1.Text;
Study;
Subject:= Memo1.Lines.Text;
Replacement:= Edit2.Text;
ReplaceAll;
Memo1.Lines.Text:= Subject;
end;
Try reformat phone numbers from 206-685-2181 format to (206) 685.2181 format to get
data back:
You can use back-references when replacing text. Text "captured" in () is given an internal
number; use number to refer to it elsewhere in the pattern 0 is the overall pattern, 1 is the first
parenthetical capture, 2 the second, ...
Example: "A" surrounded by same character: /(.)A1/
Example: to swap a last name with a first name:
var name = "Durden, Tyler";
name = name.replace(/(w+),s+(w+)/, "$2 $1");
// "Tyler Durden")
9
10. Time of day: For example. 11:30. [01][0-9]:[0-5][0-9] won't work well, because it
would allow such impossible times as 19:00 and 00:30. A more complicated construction works
better: (1[012] | [1-9]) :[0-5][0-9]. That is, a 1 followed by 0, 1, or 2, OR any digit 1-9.
Feedback @
max@kleiner.com
Literature:
Kleiner et al., Patterns konkret, 2003, Software & Support
Links of maXbox and RegEx EKON Slide Show:
http://www.softwareschule.ch/maxbox.htm
http://www.softwareschule.ch/download/A_Regex_EKON16.pdf
http://www.regular-expressions.info/
http://regexpstudio.com/tregexpr/help/RegExp_Syntax.html
http://sourceforge.net/projects/maxbox
http://sourceforge.net/apps/mediawiki/maxbox/
http://sourceforge.net/projects/delphiwebstart
10
11. 1.4 Appendix
EXAMPLE: Mail Finder
procedure delphiRegexMailfinder;
begin
// Initialize a test string to include some email addresses. This would
normally be your eMail.
TestString:= '<one@server.domain.xy>, another@otherserver.xyz';
PR:= TPerlRegEx.Create;
try
PR.RegEx:= 'b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}b';
PR.Options:= PR.Options + [preCaseLess];
PR.Compile;
PR.Subject:= TestString; // <-- tell PR where to look for matches
if PR.Match then begin
WriteLn(PR.MatchedText); // Extract first address
while PR.MatchAgain do
WriteLn(PR.MatchedText); // Extract subsequent addresses
end;
finally
PR.Free;
end;
//Readln;
end;
EXAMPLE: Songfinder
with TRegExpr.Create do try
gstr:= 'Deep Purple';
modifierS:= false; //non greedy
Expression:= '#EXTINF:d{3},'+gstr+' - ([^n].*)';
if Exec(fstr) then
Repeat
writeln(Format ('Songs of ' +gstr+': %s', [Match[1]]));
(*if AnsiCompareText(Match[1], 'Woman') > 0 then begin
closeMP3;
PlayMP3(‘..EKON_13_14_15EKON1606_Woman_From_Tokyo.mp3');
end;*)
Until Not ExecNext;
finally Free;
end;
//************************************ Code Finished******************************
11
12. 1.5 Appendix RegexBuddy in Action
1.6 Appendix String RegEx methods
.match(regexp) returns first match for this string against the
given regular expression; if global /g flag is
used, returns array of all matches
.replace(regexp, text) replaces first occurrence of the regular
expression with the given text; if global /g flag
is used, replaces all occurrences
.search(regexp) returns first index where the given regular
expression occurs
.split(delimiter[,limit]) breaks apart a string into an array of strings
using the given regular as the delimiter; returns
the array of tokens
12