Java Word Regular Expression - java

I am quite bad at Java Regular expression so I hope you guys will help me.
String variable = "My life is better ";
String variable2 = "My life01 is better";
Now I have to write a code which would return true if the string has only "life"
So I should get TRUE only for variable not for variable2 because it has life but "01" too.
~thanks.
I have tried
if (variable.contains("life")){
System.out.println("TRUE");}
It return TRUE for both.
See solution :
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Pattern p = Pattern.compile("\\blife\\b");
Matcher m = p.matcher("life0 is better");
boolean b = m.find();
System.out.println(b);
}
}

Use word boundary \b matches.
See the Java Pattern documentation for details.
Note that you may need to write it at \\b to get proper escaping. The pattern needs the string \b, which when used in .java code (and not read e.g. from a file!) needs to be written in Java-escaped form as "\\blife\\b".

Use the following regex: -
"\blife\b"
with Pattern and Matcher class. This will match for complete word. (\b denote word boundary)
You would have to use Matcher#find method, to check whether a string contains this pattern.
Note: - If you want to use String.matches, which would be appropriate here, than going with Pattern and Matcher, you would have to add .* in the front and the end. Because, String.matches matches the whole string.
For e.g: -
String str = "asdf life asdf";
System.out.println(str.matches("\\blife\\b")); // Prints false
System.out.println(str.matches(".*\\blife\\b.*")); // Prints true
In the second Regex, .* matches the string before and after life.

Use the String.matches() method and Regex \b to match word boundaries.
public class StringChecker {
String variable1 = "My life is better ";
String variable2 = "My life01 is better";
System.out.println("variable1: " + containsString(variable1));
System.out.println("variable1: " + containsString(variable2));
//Returns true if the string contains "life"
public boolean containsString(String s){
return s.matches(".*(\\blife\\b).*");
}
}

package com.rampukar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DemoRegx {
public static void main(String[] args) {
String email = "ram#example.com";
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pt_mail = Pattern.compile(EMAIL_PATTERN);
Matcher mt_mail = pt_mail.matcher(email);
if (mt_mail.matches()) {
System.out.println("Valid");
} else {
System.out.println("In-Valid");
}
System.out.println("---------------------");
String name = "Ram Pukar";
Pattern pt_name = Pattern.compile("[a-zA-Z ]{2,}");
Matcher mt_name = pt_name.matcher(name);
if (mt_name.matches()) {
System.out.println("Valid");
} else {
System.out.println("In-Valid");
}
System.out.println("---------------------");
String user = "ram123";
Pattern pt_user = Pattern.compile("[a-zA-Z0-9]{2,}");
Matcher mt_user = pt_user.matcher(user);
if (mt_user.matches()) {
System.out.println("Valid");
} else {
System.out.println("In-Valid");
}
}
}

Related

Search REGEX value in text

I'm creating this method to search the text only for the Service Order number, this information can come anywhere in the text because it is an open field for typing, I only need the first value found if you have more than one service order.
example text:
Please check service order number 1-202012345678 for vehicle repair toyota Corolla red
Could someone help me find the error?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Encontra_Ordem {
private static final Pattern PATTERN = Pattern.compile(".*([1#][-#]\\d{12}).*");
public static String buscaordemnotexto(String texto) {
String valor = "";
Matcher matcher = PATTERN.matcher(texto);
if(matcher.matches() && matcher.groupCount() == 1){
String numerodaordem = matcher.group(1);
valor += numerodaordem;
}
return valor;
}
}
With the given data I'd suggest this solution:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Encontra_Ordem {
private static final Pattern PATTERN = Pattern.compile("\\b\\d-\\d{12}\\b");
public static String buscaordemnotexto(String texto) {
String valor = "";
Matcher matcher = PATTERN.matcher(texto);
if (matcher.find()) {
String numerodaordem = matcher.group();
valor += numerodaordem;
}
return valor;
}
public static void main(String[] args) {
System.out.println(buscaordemnotexto("asda sd asd asd asd sa 2-202012345678 ttttttt 1-202012345678"));
}
}
Output
2-202012345678
Explanation
Here's the breakdown of the RegEx I wrote (click on it to make it more readable):
I also used matcher.find() inside an if block so that the content of matcher.group() will be the first RegEx match.
The find() Method
Put simply, the find() method tries to find the
occurrence of a regex pattern within a given string. If multiple
occurrences are found in the string, then the first call to find()
will jump to the first occurrence. Thereafter, each subsequent call to
the find() method will go to the next matching occurrence, one by one.
Sources
https://regexr.com
https://www.baeldung.com/java-matcher-find-vs-matches

Print out the last match of a regex

I have this code:
String responseData = "http://xxxxx-f.frehd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/.m3u8";
"http://xxxxx-f.frehd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/.m3u8";
String pattern = ^(https://.*\.54325)$;
Pattern pr = Pattern.compile(pattern);
Matcher math = pr.matcher(responseData);
if (math.find()) {
// print the url
}
else {
System.out.println("No Math");
}
I want to print out the last string that starts with http and ends with .m3u8. How do I do this? I'm stuck. All help is appreciated.
The problem I have now is that when I find a math and what to print out the string, I get everything from responseData.
In case you need to get some substring at the end that is preceded by similar substrings, you need to make sure the regex engine has already consumed as many characters before your required match as possible.
Also, you have a ^ in your pattern that means beginning of a string. Thus, it starts matching from the very beginning.
You can achieve what you want with just lastIndexOf and substring:
System.out.println(str.substring(str.lastIndexOf("http://")));
Or, if you need a regex, you'll need to use
String pattern = ".*(http://.*?\\.m3u8)$";
and use math.group(1) to print the value.
Sample code:
import java.util.regex.*;
public class HelloWorld{
public static void main(String []args){
String str = "http://xxxxx-f.akamaihd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/index_0_av.m3u8" +
"EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2795000,RESOLUTION=1280x720,CODECS=avc1.64001f, mp4a.40.2" +
"http://xxxxx-f.akamaihd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/index_6_av.m3u8";
String rx = ".*(http://.*?\\.m3u8)$";
Pattern ptrn = Pattern.compile(rx);
Matcher m = ptrn.matcher(str);
while (m.find()) {
System.out.println(m.group(1));
}
}
}
Output:
http://xxxxx-f.akamaihd.net/i/world/open/20150426/1370235-005A/EPISOD-1370235-005A-016f1729028090bf_,892,144,252,360,540,1584,2700,.mp4.csmil/index_6_av.m3u8
Also tested on RegexPlanet

How to write a regex in java to check whether a string contains two chars space and three integers?

I have a string String myString = "abc,QWAB 123,cdef";.
How to write regex to check whether my string has AB (space)123. I don't want to consider QW. Also number 123 will be one digit or two digit or three digit, Always it will not be three digit.
Please help.
Pattern pat = Pattern.compile( "AB \\d{1,3}" );
^[^,]+,AB \d{1,3},.*$
Try this.This should do it.See demo.
https://regex101.com/r/gX5qF3/8
Try something like:
String myString = "abc,QWAB 123,cdef";
if (myString.matches(".*AB [0-9]{1,3}.*")) {
System.out.println("Yes it mateched");
} else {
System.out.println("Hard luck");
}
This this:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Hello world!
*
*/
public class App {
static String myString = "abc,QWAB 123,cdef";
static String abcPattern = "(AB[\\s]{1}\\d{1,3})";
public static void main(String[] args) {
Pattern pattern = Pattern.compile(App.abcPattern, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(myString);
if (matcher.find()) {
System.out.println(matcher.group());
} else {
System.out.println(" No mach found ");
}
}
}

Concatenation of a string and a regex in java

I want to concatenate a regex and a string and want to compare the resultant string with another string.How can I do that in java?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatching {
public static void main(String aaa[])
{
String testStr="anjaneyPANDEY";
String regEx = "([A-Z])";
Pattern pattern = Pattern.compile(regEx);
Matcher matcher = pattern.matcher(testStr);
String st="anjaney"+regEx;
if(testStr.matches(st))
System.out.println("YES");
else System.out.println("NO");
}
}
It seems that you forgot to add + in your regex to let it match one or more uppercase character. You should use [A-Z]+ since matches checks if entire string can be matched with regex.
Also you should use created Matcher instance instead of testStr.matches(st) to not recompile every time your pattern. So your code can look like
String regEx = "([A-Z]+)";
String st = "anjaney" + regEx;
Pattern pattern = Pattern.compile(st);
Matcher matcher = pattern.matcher(testStr);
if (matcher.matches())
System.out.println("YES");
else
System.out.println("NO");
This approach is OK if you know that string you want to combine with regex doesn't have any regex metacharacters like ( * + and so on.
But if you are not sure about it then you need to create escape such metacharacters. In that case you can use Pattern.quote() method. So instead of
String st = "anjaney" + regEx;
you can use
String st = Pattern.quote("anjaney") + regEx;
try it:
String testStr = "anjaneyPANDEY";
String regEx = "([A-Z])+";
String st = "anjaney" + regEx;
if (testStr.matches(st)) {
System.out.println("YES");
} else {
System.out.println("NO");
}

one regular expression that can work for two different string url's

public String getContextName() {
String contextName = FacesContext.getCurrentInstance()
.getExternalContext().getRequestContextPath();
String uri = "localhost/gar/garmin-first/gar_home";
Pattern pat=Pattern.compile("/(.*?)/(.*)/");
Matcher matcher = pat.matcher(uri);
matcher.find();
System.out.println("matched"+matcher.group(1)+matcher.group(2));
if (StringUtil.isNotEmpty(contextName) &&
contextName.contains(matcher.group(1))) {
return matcher.group(2);
}
return matcher.group(1);
}
The output in the console will be printed as group(1) = gar,and group(2) = garmin-first, but what I really need is one regular expression that can work for both the cases. The other case is:
String uri = "localhost/garmin-first/gar_home";
In this case I need the output as group(1) = garmin-first and group(2) should be left empty. Can you please help me out
with a regular expression that can work for both the cases please.
package test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test1
{
public static void main(String[] args)
{
String[] strings = new String[]
{ "localhost/gar/garmin-first/gar_home", "localhost/garmin-first/gar_home" };
Pattern pat = Pattern.compile("(?<=/)(.*?)(?=/)");
for(String s : strings)
{
System.out.println("For: " + s);
Matcher matcher = pat.matcher(s);
while (matcher.find())
{
System.out.println(matcher.group());
}
}
}
}
I've changed the regex subtly so that we are looking for words that are surrounded by "/".
Hopefully you can find a useful way to get the parts you need because I don't think .group(1) and .group(2) will work now that we are looking for multiple matches in the same string.

Categories