How to match a string which is in particular format? - java

I need to check whether my string follows a particular pattern or not. My string will always start with text_data_ and then followed by a number always as shown below
text_data_123
text_data_124
text_data_126
text_data_127
text_data_128
Now how can I check whether the string I am getting is in above format:
String value = getData();
// but this doesn't work?
if(value.matches("text_data(?<=_)\\d+")) {
// found a match
}
What's wrong I am doing?

The lookbehind does not assert that what immediately precedes the current position is _.
You don't need to use lookbehind for this.
if(value.matches("text_data_\\d+")) { ... }

using 'startsWith(String prefix)' method in String Class.
if (value.startsWith("text_data_")) {
// found a match
}

You could use:
If(value.contains("text_data_")){
}
But I would suggest using dreaming cat's solution.

Related

In Java, how do I check if a string consists of both letters and numbers, but only letters and numbers?

I tried this:
private static void isLetterandNumberCombo(Tokens token) {
if (token.getContents().matches("^(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+$")){
token.setValid(false);
}
}
but the input 123f45 still does not set the token to valid as I thought it would
Your solution is fine. You just need to add the case-insensitive flag ((?i)) to match lowercase letters. And matches() looks for a full match, so you don't need the anchors at the beginning and end:
(?i)(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+
Give this a whirl
private static boolean isLetterandNumberCombo(Tokens token) {
String regex = "^[a-zA-Z0-9]+$";
Pattern pattern = Pattern.compile(regex);
return pattern.matcher(token.getContents()).matches();
}
You'll get back true or false if the token is valid.
I would go with:
^[A-Za-z\d]*(([A-Za-z]\d)|(\d[A-Za-z]))[A-Za-z\d]*$
The idea is that a valid string will have either a letter followed by a number or the opposite somewhere, and other optional letters or numbers before or after.
A simple regex would do the job:
Change your function to:
private static void isLetterandNumberCombo(Tokens token) {
token.setValid(token.getContents() != null && token.getContents().matches("[a-zA-Z0-9]+"));
}

Convert this pattern to regex for Pattern.matches(..)

Some of my strings may contain a substring that looks like #[alph4Num3ric-alph4Num3ric] , where I will find the alpha numberic id and replace it with a corresponding text value mapped to the associated key in a map.
My first inclination was to check if my string.contains("#[") but I want to be more specific
so now I am looking at Pattern.matches( but am unsure of the regex and total expression
how would I regex for #[ ...... - .... ] in the Pattern.matches method, it must also account for dashes. So I'm not sure what needs to be escaped in this syntax or wildcarded, or more.
I am also not 100% sure if this is the best message. I want to get a boolean from Pattern.matches first, and then get the real value and modify the string with those values, which seems good enough, but I want to minimize computations.
Plese try this ,
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String expression = "String contains #[alph4Num3ric-alph4Num3ric] as substring";
Pattern pattern = Pattern
.compile("\\#\\[([a-zA-Z0-9]+)-([a-zA-Z0-9]+)\\]");
Matcher matcher = pattern.matcher(expression);
while (matcher.find()) {
System.out.println("matched: "+matcher.group());
System.out.println("group1: "+matcher.group(1));
System.out.println("group2: "+matcher.group(2));
System.out
.println("after replace "+expression.replace(matcher.group(1), "customkey"));
}
}
}
output :
matched: #[alph4Num3ric-alph4Num3ric]
group1: alph4Num3ric
group2: alph4Num3ric
after replace: String contains #[customkey-customkey] as substring
Try using this:
/#[(a-zA-Z0-9-)+]/
I haven't given it a try but hope this would help. Also if it returns an error then add a backward slash between 9 and - e.g. /#[(a-zA-Z0-9-)+]/

How can i find whether the string starts with 's','r','p' in java

Example: This is my string,
String sample = "s5656";
If the first character of the string contains 's' or 'p' or 'r' means i should remove the character,Otherwise i have to
return the original string.
Is there any optimized way to do that like "regex" or "StringUtils" in apache common?
Why do you want to add 3rd party jar for this kind of simple requirement? You can try as follows
String sample = "s5656";
if(sample.startsWith("s")||sample.startsWith("r")||sample.startsWith("p")){
// do necessary
}else{
// do necessary
}
String#startsWith()
A simple regex could solve your problem :
public static void main(String[] args) {
String s = "s5656s";
System.out.println(s.replaceFirst("^[spr]", "")); // a String which begins with s,p or r
}
O/P:
5656s
PS: regex here leads to smaller/simpler but inefficient code. Use Ruchira's answer for a rather long but efficient code. :)
^(s|p|r)
Try this.Use yourString.replaceAll() / replaceFirst() with empty string.Use m.
See demo.
http://regex101.com/r/dZ1vT6/49
I should go for replaceAll function with multiline modifier (?m).
String s = "s5656s\n" +
"r878dsjhj\n" +
"fshghg";
System.out.println(s.replaceAll("(?m)^[spr]", ""));
Output:
5656s
878dsjhj
fshghg

Java : Omitting a Word in a String

I have a String , from which i need to omit a particular word from it .
As shown below the String may contain a Word "Baci" OR "BACI" in it
I have written a sample program shown below which works fine , but i want to know if there is better way to do it ??
public class Test {
public static void main(String args[]) {
String str = "Mar 14 Baci WIC";
if(str!=null&&!str.isEmpty())
{
if(str.contains("Baci") || str.contains("BACI"))
{
str = str.replaceAll("(?i) Baci", "");
}
}
System.out.println(str);
}
}
I think better way here will be to not additionally check the existance of "Baci", i.e. without the following if check
if(str.contains("Baci") || str.contains("BACI"))
You could improve it a little by using the \b regexp (which matches a "word boundary") :
str = str.replaceAll("(?i) Baci\\b", "");
That way, you code will not replace "my bacil is..." with "myl is..."
Your second if condition is unnecessary, since replaceAll() will replace zero or more occurrences of the String without error.
you can .toUpperCase your String and then only ask for contains("BACI"). Inside the if block, then just call replace twice with both Baci and BACI.
Thinking it again, I think it's better just calling replace twice without asking if your String contains it or not. If it doesn't find anything to replace, then it won't replace nothing.
Hope it would be useful!

How to validate string using regex in java

I want to validate a string which donot have numeric characters.
If my string is "javaABC" then it must be validated
If my string is "java1" then it must not be validated
I want to restrict all the integers.
Try this:
String Text = ...;
boolean HasNoNumber = Text.matches("^[^0-9]*$");
'^[^0-9]*$' = From Start(^) to end ($), there are ([...]) only non(^) number(0-9). You can use '\D' as other suggest too ... but this is easy to understand.
See more info here.
You can use this:
\D
"\D" matches non-digit characters.
Here is one way that you can search for a digit in a String:
public boolean isValid(String stringToValidate) {
if(Pattern.compile("[0-9]").matcher(stringToValidate).find()) {
// The string is not valid.
return false;
}
// The string is valid.
return true;
}
More detail is here:
http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html
The easiest to understand is probably matching for a single digit and if found fail, instead of creating a regexp that makes sure that all characters in the string are non-digits.

Categories

Resources