Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi i want to do some validations.I used to put regex in JS but im new to regex in java, so i tried to make up a code on similar lines in java.
Here is what i did.
1)Check whether first character in string is alphanumeric.
2)Check whether the string atleast 1 number.
so i wrote a code, but it is always returning false.I am not sure if i'm doing this correctly.
private static boolean checkEmbeddedPassword(final String field) {
boolean returnValue=true;
String testpatternAlpha="/^[A-Za-z0-9].+$/";
String testNumber="/[0-9]/";
Pattern pattern=Pattern.compile(testpatternAlpha);
Pattern pattern2=Pattern.compile(testNumber);
Matcher matcher = pattern.matcher(field);
Matcher matcher2 = pattern2.matcher(field);
boolean firstChar=matcher.matches();
boolean numberFlag=matcher2.matches();
System.out.println("-----the value of pwd iss-----"+field);
System.out.println("---------Regex---------Out--put-----"+firstChar);
System.out.println("---------Regex---------Out- for numeral-put-----"+numberFlag);
if(firstChar){
returnValue=false;
}
else if(field.contains(" "))
{
System.out.println("-----------cannot have space------");
returnValue=false;
}
else if(numberFlag)
{
returnValue=false;
}
return returnValue;
}
You don't need the / prefix and suffix in Java:
String testpatternAlpha="^[A-Za-z0-9].+$";
Also in your situation you'll want to be using Matcher.find rather than Matcher.matches. You can read why in the API documentation: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Matcher.html
we do not use / on the beginning and end of the regex in java.
try this...
String testpatternAlpha="^[A-Za-z0-9].+$"; // first character in string is alphanumeric
String testNumber="[0-9]"; //test single number
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Saying that there are String A = "aabbccdd" and String B = "abcd",
is there any way to remove the matching characters of String B towards String A for only one time?
Expected output is A = "abcd".
I know it will solve the problem when using for loops, but is there any simpler way to do it?
For example, using replaceAll or regular expressions?
you can use distinct() method
public static void main(String[] args) {
String str = "aabbccdd";
String result = str.chars().distinct().boxed()
.map(c -> (char) (c.intValue()))
.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(result);
}
you can use the regex for that
A = A.replaceAll("([a-z]+)\1","");
can find out more about regex here https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to split a String which is a file's name (ex: DIS_LU0786738343_20170608.pdf, KID_AMEV_20170608.pdf, Evolution-DIS_20170512.csv, Offres-invest_20170608.csv, OST_20170608.csv) to get the last part.
For example for the String DIS_LU0786738343_20170608.pdf I want to get only 20170608 which will be transformed on a Date object.
I've been googling this and I found a solution using Regular Expressions:
String regex = "some regex expression";
String fileName = "DIS_LU0786738343_20170608.pdf";
System.out.println(Arrays.toString(fileName.split(regex)));
This will return an Array like this : [DIS_LU0786738343_, 20170608]
So anyone can help me make the Regular Expression to do so ?
String fileName = "DIS_LU0786738343_20170608.pdf";
int startIdx = fileName.lastIndexOf("_");
int endIdx = fileName.lastIndexOf(".");
String finalStr=fileName;
if (startIdx > 0 && endIdx > 0)
finalStr = fileName.substring(startIdx + 1, endIdx);
System.out.println(finalStr);
I think this should work for you.
I dropped down the RegEx thing and found another solution that I want to share with anyone who'll need it in the future :
private LocalDate getDateFromPriipsDoc(File file) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
String fileName = FilenameUtils.getBaseName(file.toString());
String dateInString = fileName.substring(fileName.lastIndexOf("_") + 1);
return LocalDate.parse(dateInString, formatter);
}
Do not hesitate to share another solution with RegEx ;)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a long string of digits in Java. I want to find of the string contains any one of the digits 0,1,4,6,8,9 or not. I do not want to check if my string contains just any random digits or not.
I don't care how many times the digit is present. If any one of the above digits is present in the string even once, I want to stop right there and return true.
what regex can be used to match this string?
Is there any faster way to do it instead of using regex?
I am using Java 8.
EDIT: I already found lots solutions online for checking if a string contains digits or not. Those solutions don't work here because I want to optimally find out if my string (of length~10^15 characters) contains specific digits or not.
You can use the pattern .*[014689].* along with String.matches():
String input = "1 Hello World";
if (input.matches(".*[014689].*")) {
System.out.println("Match!");
}
Assuming your String is so very big that you have to read it from an InputStream, I'd advise something of the likes :
public static final Pattern TO_MATCH = Pattern.compile("[014689]");
public static boolean hasDigits(InputStream is, int bufferSize){
BufferedReader l_read = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()),bufferSize);
return l_read.lines().filter(s -> TO_MATCH.matcher(s).find()).findAny().isPresent();
}
Where you can tweak buffersize for performance.
if (preg_match('/[^|]/', $string)) {
// string contains characters other than |
}
or:
if (strlen(str_replace('|', '', $string)) > 0) {
// string contains characters other than |
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I got a java question which is Given a string, return the string made of its first two chars, so the String "Hello" yields "He".
If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "".
Note that str.length() returns the length of a string.
public String firstTwo(String str) {
if(str.length()<2){
return str;
}
else{
return str.substring(0,2);
}
}
I'm wondering is there any other way can solve this question?
Your code looks great! If you wanted to make it shorter you could use the ternary operator:
public String firstTwo(String str) {
return str.length() < 2 ? str : str.substring(0, 2);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have sentences like:
Slno:0 ahdhajdhjahdjahjdhahd <>
Slno:1 ahdhajdhjahdjahjdhahd <>
Slno:2 ahdhajdhjahdjahjdhahd <>
I want to compare with the first 5 charters as "Slno:x" where x is a integer.
if that condition is met I want to print the rest of the lines. and the remove the last <>
so the output looks like:
ahdhajdhjahdjahjdhahd
ahdhajdhjahdjahjdhahd
ahdhajdhjahdjahjdhahd
I tried doing:
if string1.charAt(1)=='S' for all charcaters and than printed from string1[5] to end.
if that conditions are true. Looking for a more better logic
If i understand your requirement correctly i think this would work.try this:
public static void main(string..args) {
String s1= "Slno:0 ahdhajdhjahdjahjdhahd <>";
String[] sSplit = s1.split("\\s");
String f[]= sSplit[0].split(":");
;
if(f[0].equals("Slno") && checkInt(f[1])) {
System.out.println(sSplit[1]);
}
}
public static boolean checkInt(String i) {
try {
Integer.parseInt(i);
return true;
}
catch(Exception ex){
return false;
}
}
You can use Regex and substring.. if you spaces between your sentences: -
String s1 = "Slno:0 ahdhajdhjahdjahjdhahd <>";
if (s1.substring(0, 6).matches("Slno:\\d")) {
System.out.println(s1.substring(7, s1.length() - 3));
}
Output: -
ahdhajdhjahdjahjdhahd
You can try this,
Example: "Slno:0 ahdhajdhjahdjahjdhahd <>"
Split the Sentence to three parts using split method setting delimiters as space.
StringOne = "Slno:0"
StringTwo = "ahdhajdhjahdjahjdhahd"
StringThree = "<>"
Use contains method to match the input. If the given input matches the first part of the string then print the second part of the string.