Quantcast
Channel: Kushal's Java Blog | Software Engineering Blog » Java Regular Expressions - Kushal's Java Blog | Software Engineering Blog
Viewing all articles
Browse latest Browse all 12

How to find if a string is contained in another string using regex in Java?

$
0
0

This is a simple utility to find out (through regular expressions) if a string is contained in another string. The string to search may be located anywhere in the text to look into (i.e. it may lie at the beginning, at the end or somewhere in the middle)

package com.kushal.tools;

/**
 * @Author Kushal Paudyal
 * Last Modified On 2011/05/13
 * 
 * A simple utility to find out (through regular expressions) if a string is 
 * contained in another string. The string to search may be located anywhere
 * in the text to look into.
 */
import java.util.regex.Pattern;

public class RegexNotContains {

	static String textToLookInto = "This line is not written in golden letters.";
	static String wordToFind = "golden";
	static String notContainsRegex = "[\\w\\W\\s]*" + wordToFind + "[\\w\\W\\s]*";

	public static void main (String [] args ) {
		
		checkIfContains(textToLookInto, wordToFind);
		
	}
	
	public static boolean checkIfContains(String textToLookInto, String wordTofind )
	{
		boolean matches=Pattern.matches(notContainsRegex,textToLookInto);
		if (matches) {
			System.out.println("Word \'"+wordToFind+"\' was found in the line: "+textToLookInto);
		} else {
			System.out.println("Word \'"+wordToFind+"\' was NOT found in the line: \'"+textToLookInto+"\'");
		}
		return matches;
	}
}

Originally posted 2011-05-17 20:29:01.

Share


Viewing all articles
Browse latest Browse all 12

Trending Articles