Regex Questions :

Answers

  1. Find any text which has Letters which starts with Capital Letters only?(Example : Java)
  2. Find any words which does not contain character en in it? (Example : word “engine” is not be found in the search)
  3. Find repeated words which are together? (Exampel : “the the” word together should not appear )

Random Text Below for these questions

  1. Examples are the open source PCRE engine (used in many tools and languages like PHP), the .NET
    regular expression library, and the regular expression package included with version 1.4 and later of the Java
    JDK. I will point out to you whenever differences in regex flavors are important, and which features are
    specific to the Perl-derivatives mentioned above.
    Give Regexes a First Try
    You can easily try the following yourself in a text editor that supports regular expressions, such as EditPad
    Pro. If you do not have such an editor, you can download the free evaluation version of EditPad Pro to try
    this out. EditPad Pro’s regex engine is fully functional in the demo version. As a quick test, copy and paste
    the text of this page into EditPad Pro. Then select Search|Show Search Panel from the menu. In the search
    pane that appears near the bottom, type in «regex» in the box labeled “Search Text”. Mark the “Regular
    expression” checkbox, and click the Find First button. This is the leftmost button on the search panel. See
    how EditPad Pro’s regex engine finds the first match. Click the Find Next button, which sits next to the Find
    First button, to find further matches. When there are no further matches, the Find Next button’s icon will
    flash briefly.
    Now try to search using the regex «reg(ular expressions?|ex(p|es)?)» . This regex will find all
    names, singular and plural, I have used on this page to say “regex”. If we only had plain text search, we would
    have needed 5 searches. With regexes, we need just one search. Regexes save you time when using a tool like
    EditPad Pro. Select Count Matc1+1=2hes in the Search menu to see how many times this regular expression can
    match the file you have open in EditPad Pro.
    If you are a programmer, your software will run faster since even a simple regex engine applying the above
    regex once will outperform a state 1+1=2 of the art plain text search algorithm searching through the data five times.
    Regular
    expressions also
    reduce
    development time.
    With a regex
    engine, it takes
    only one line (e.g.
    in Perl, PHP, Java
    or .NET) or a
    couple of lines
    (e.g. in C using
    PCRE) of code to,
    say, check if the
    user’s input looks
    like a valid email
    address.

RegEx engines

Regular Expressions work behind the scenes using RegEx engines, there are mainly two types of RegEx engines text-directed(DNF) and regex-directed(NFA) engine.

There is an easy way to find which RegEx engine is your application using, using put the text “hello world” in your application and search for “hello|hello world” . If your application returns hello then your application is using a regex directed engine, if your application returns “hello world” as the result then it is using a text-directed engine.

regex-directed engine is always eager and will return the left most result even if a better match can be found later

When applying «cat» to “He captured a catfish for his cat.”, the engine will try to match the first
token in the regex «c» to the first character in the match “H”. This fails. There are no other possible permutations of this regex, because it merely consists of a sequence of literal characters. So the regex engine tries to match the «c» with the “e”. This fails too, as does matching the «c» with the space. Arriving at the 4th character in the match, «c» matches „c”. The engine will then try to match the second token «a» to the 5th character, „a”. This succeeds too. But then, «t» fails to match “p”. At that point, the engine knows the regex cannot be matched starting at the 4th character in the match. So it will continue with the 5th: “a”. Again, «c» fails to match here and the engine carries on. At the 15th character in the match, «c» again matches „c”. The engine then proceeds to attempt to match the remainder of the regex at character 15 and finds that «a» matches „a” and «t» matches „t”.

The entire regular expression could be matched starting at character 15. The engine is “eager” to report a match. It will therefore report the first three letters of catfish as a valid match. The engine never proceeds beyond this point to see if there are any “better” matches. The first match is considered good enough.

Meta characters in Regex

Below are the meta characters in Regex i.e these characters has special meaning and if we want to search this characters using Regex we need to escape these characters using a black slash \ .

10 Meta characters
[ ]
\
^
$
.
|
?
*
+
( )

Non printable characters

You can use special characters to match non printable character in regular expression.

\tTab characterASCII 0x09
\rCarriage Return0x0D
\nNew Line feed0x0A
\vVertical tab0x0B

In the Latin-1 character set, the copyright symbol is character
0xA9. So to search for the copyright symbol, you can use «\xA9». Another way to search for a tab is to use «\x09». Note that the leading zero is required.

Most regex flavors also support the tokens «\cA» through «\cZ» to insert ASCII control characters. The letter after the backslash is always a lowercase c. The second letter is an uppercase letter A through Z, to indicate Control+A through Control+Z. These are equivalent to «\x01» through «\x1A» (26 decimal). E.g. «\cM» matches a carriage return, just like «\r» and «\x0D». In XML Schema regular expressions, «\c» is a shorthand character class that matches any character allowed in an XML name.

If your regular expression engine supports Unicode, use «\uFFFF» rather than «\xFF» to insert a Unicode character. The euro currency sign occupies code point 0x20AC. If you cannot type it on your keyboard, you can insert it into a regular expression with «\u20AC».

Quantifiers in Regular Expression

We can use Quntifiers to Specify Number of Occurrences to Match

Expression Meaning
a Exact One ‘a’
a+ At least One ‘a’
a* Any number of a (including 0 no of ‘a’)
a? At most on ‘a’
package demo.example4;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Tyson
 *
 *         Search for number of occurrences in regular expression The group()
 *         method is very important here to see what is matched
 */
public class Demo4 {
	public static void main(String[] args) {
// add \ before\s for space because \ is a escape character
		printMatch("a", "abaabaaab", "Search for Character 'a' only");
		printMatch("a+", "abaabaaab", "Search for single or sequence of 'a' as a single match");
		printMatch("a*", "abaabbaaab", "Search for single or sequence of 'a' or zero 'a' as a single match");
		printMatch("a?", "abaabaaab", "Search for atmost one 'a' or zero 'a' as a single match");
		printMatch("a{2}", "abaabbaaab", "Search for a occured exactly 2 times as a single String");
	}

	public static void printMatch(String regularExpression, String targetString, String comment) {
		Pattern p = Pattern.compile(regularExpression);
		Matcher m = p.matcher(targetString);
		System.out.println("===" + regularExpression + "===in===" + targetString + "=== " + comment);
		while (m.find()) {
			System.out.println(m.start() + "..." + m.group());
		}
		System.out.println("\n");
	}
}

Character classes in Regular Expression

Expression Meaning
[abc] Either ‘a’ or ‘b’ or ‘c’
[^abc] Except ‘a’, or ‘b’ or ‘c’
[a-z] Any lower case alphabet symbol
[A-Z] Any upper case alphabet symbol
[a-zA-Z] Any alphabet symbol
[0-9] Any digit from 0-9
[a-zA-Z0-9] Any alphanumeric character
[^a-zA-Z0-9] Special Character i.e Except Alphanumeric characters
package demo.example2;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Tyson
 *
 *         Searching for a group of things together
 *
 *         Character Classes Example
 *
 */
public class Demo2 {
	public static void main(String[] args) {
		printMatch("[abc]", "a7b@2#9", "Find a or b or c");
		printMatch("[^abc]", "a7b@2#9", "Find Excepet a or b or c");
		printMatch("[a-z]", "a7b@2#9", "Find anything between a to z");
		printMatch("[0-9]", "a7b@2#9", "Find any digit");
		printMatch("[a-zA-Z0-9]", "a7b@2#9", "Find any alphanumeric value");
		printMatch("[^a-zA-Z0-9]", "a7b@2#9", "Find any special characters ie excepet alphanumeric");
	}

	public static void printMatch(String regularExpression, String targetString, String comment) {
		Pattern p = Pattern.compile(regularExpression);
		Matcher m = p.matcher(targetString);
		System.out.println("===" + regularExpression + "===in===" + targetString + "=== " + comment);
		while (m.find()) {
			System.out.println(m.start() + "..." + m.group());
		}
		System.out.println("\n");
	}
}

Predefined Character classes in Regular Expression

Expression Meaning
\s Space Character
\S Except Space any character
\d  Any Digit
\D Except Digit any character
\w Any word character [a-zA-Z0-9]
\W Special Chracter i.e Except word character
. Any character
package demo.example3;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Tyson
 *
 *         Search for chracters which already have special meaning in Java Regex
 */
public class Demo3 {
	public static void main(String[] args) {
		// add \ before\s for escape because \ is a escape character
		printMatch("\\s", "a7b k@9", "Search for Space");
		printMatch("\\S", "a7b k@9", "Search for anything Except Space");
		printMatch("\\d", "a7b k@9", "Search for only digit");
		printMatch("\\D", "a7b k@9", "Search for aything except digit");
		printMatch("\\w", "a7b k@9", "Search for alphanumeric character");
		printMatch("\\W", "a7b k@9", "Search for Special Character");
		printMatch(".", "a7b k@9", "Search for Any Character");
	}

	public static void printMatch(String regularExpression, String targetString, String comment) {
		Pattern p = Pattern.compile(regularExpression);
		Matcher m = p.matcher(targetString);
		System.out.println("===" + regularExpression + "===in===" + targetString + "=== " + comment);
		while (m.find()) {
			System.out.println(m.start() + "..." + m.group());
		}
		System.out.println("\n");
	}
}

Output :

Basic Example of Regular Expression (Search for a single word)

Important Classes in Regular Expression

  • Pattern
    • A Pattern object represents a compiled version of regular expression.
    • We can create a Pattern Object by using compile() of Pattern Class
      public Static compile(String regularExpression)
      How to create a Pattern Object?
      Pattern p = Pattern.compile(“ab”);
  • Matcher
    • We can Use Matcher Object to Match the given Pattern in the target String.
    • We can Create Matcher Object by using matcher() of Pattern class.
      public Matcher matcher(String target)
      How to create a Matcher Object ?
      Matcher m = p.matcher(“ababbaba);
package demo.example1;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author Tyson
* Pattern String to find : ab
* Target String : ababbaba
* If available where it is available and how many times it is available
*/

public class Demo1 {
	public static void main(String[] args) {
		int count = 0;
		//Create a Pattern object of the String to be Searched
		//Pattern object represents the compiled version of regular expression string
		//Equivalent java object of Regular Expression word to be searched
		Pattern p = Pattern.compile("ab");
		/**
		 * Pattern is a factory method i.e If using class name we are calling a method
		 * and it returns object of the same class then we call it as a Static Factory method
		 */
		//Create a Matcher object of the String which is the Target string
		//in which pattern has to be searched
		Matcher m = p.matcher("ababbaba");
		//Find the matches in the Matcher object
		while(m.find()){
			//Print the start and end index of the match
			System.out.println(m.start()+"..."+m.end()+"..."+m.group());
			//Remember end() method returns value +1
			//group() method displays what got matched in the target
			count = count + 1;
		}
		System.out.println("Number of occurances : "+count);
	}
}
Output

Introduction to regular expression

  1. Regular Expression concept came in java in 1.4 version.
  2. Regular Expression: It is an expression to represent a group of String objects according to a particular pattern.
  3. Mostly used to validate user input in html forms.
  4. Pattern matching application i.e find in a notpad program.
  5. While designing translators example in compiler.
  6. Digital Circuit development uses regular repressions.
  7. Communication protocol development example TCP/UDP.

Changing the build file name and directory in Gradle

You can point to a build file and execute the task inside that build file using the below command.

gradle --build-file <file_name>.gradle -q <task_name>
gradle -b <file_name>.gradle -q <task_name>

You can execute task in any project directory by using the below command

gradle --project-dir <project_directory> -q <task_name>

You can execute both of above command together sample below

Basic Gradle Commands

Logging options in Gradle

CommandDescription
–quite (or -q)Log errors only.
–debug (or -d)This option provides
a lot of output with information about the steps and classes used to run the
build.
–warn(or -w)Set log level to warn.Less verbose that debug
–info (or -i)To get a better insight into the steps that are executed for our task
–stacktrace (or -s)Print out the stacktrace for all exceptions.
–full-stacktrace
(or -S)
Print out the full (very verbose) stacktrace for all exceptions.
gradle -q task
gradle -i task
gradle -d task
gradle -qs task
gradle -is task
gradle -ds task
gradle -qS task
gradle -iS task
gradle -dS task

Help in gradle

gradle -q help 

Find details about task in gradle

gradle -q help --task <task_name>

List of tasks in gradle

gralde -q tasks

List of properties in Gradle

gradle -q properties

Running tasks without actually executing them (dry run)

With the help of –dry-run option or (-m) we can actually run the task without actually executing them, Gradle builds up a DAG(Direct Acyclic Graph) with all the task needed to be executed in that build

gradle --dry-run build
gradle -m build

Gradle Demon

Check status of Gradle Demon

gradle --status  //Status of Demin

Disabling Demon in gradle via properties file

org.gradle.daemon=false