I've got the following code:
public class testMatch {
public static void main(String[] args) {
String dummyMessage = "asdfasdfsadfsadfasdf 3 sdfasdfasdfasdf";
String expression = "3";
if (dummyMessage.matches(expression)){
System.out.println("MATCH!");
} else {
System.out.println("NO MATCH!");
}
}
}
I'd expect this to be a successful match as the dummyMessage contains the expression 3 but when I run this snippet the code prints NO MATCH!
I don't get what I'm doing wrong.
OKAY STOP ANSWERING! .*3.* works
This is an over simplification of an issue I have in some live code, the regex is configurable, and up until now matching the entire string has been okay, I've now had to match a part of the string and was wondering why it wasn't working.
It matches against the whole string, i.e. like ^3$ in most other regex implementations. So 3 does not match e.g. 333 or your string. But .*3.* would do the job.
However, if you just want to test if "3" is contained in your string you don't need a regex at all. Use dummyMessage.contains(expression) instead.
String#matches(regex) Tells whether or not this string matches the given regular expression.
your string dummyMessage doesn't match expression, as it tries to check if dummyMessage is 3 you probably want String.contains(charseq) instead.
String dummyMessage = "asdfasdfsadfsadfasdf 3 sdfasdfasdfasdf";
String expression = "3";
if (dummyMessage.contains(expression)){
System.out.println("MATCH!");
} else {
System.out.println("NO MATCH!");
}
You should match the whole string for matches to return true. Maybe try using .*3.*.
It will match for such regex: .*3.*
Use contains(expression)
String dummyMessage = "asdfasdfsadfsadfasdf 3 sdfasdfasdfasdf";
String expression = "3";
if (dummyMessage.contains(expression)) {
System.out.println("MATCH!");
} else {
System.out.println("NO MATCH!");
}
By default String#matches() test if string matches regular expression completely. To make it working replace
expression = "3"
with
expression = ".*3.*"
To match substring in string use Matcher#find() method.
your regexp should rather be .*3.*
the matches() method on String class check if the whole string matches.
I modified your code to:
public class testMatch
{
public static void main(String[] args)
{
String dummyMessage = "asdfasdfsadfsadfasdf 3 sdfasdfasdfasdf";
String expression = ".*3.*";
if (dummyMessage.matches(expression))
{
System.out.println("MATCH!");
}
else
{
System.out.println("NO MATCH!");
}
}
}
and it now works
You may be looking for matcher.find:
String message = "asdfasdfsadfsadfasdf 3 sdfasdf3asdfasdf";
String expression = "3";
// Really only need to do this once.
Pattern pattern = Pattern.compile(expression);
// Do this once for each message.
Matcher matcher = pattern.matcher(message);
if (matcher.find()) {
do {
System.out.println("MATCH! At " + matcher.start() + "-" + matcher.end());
} while ( matcher.find() );
} else {
System.out.println("NO MATCH!");
}
Change the original regex accordingly - it is currently incorrect and does not match:
String expression = "(.*)3(.*)";
Or just use String.contains() - I'd say that is a lot more appropriate for this situation.
Either you do it that way:
String dummyMessage = "asdfasdfsadfsadfasdf 3 sdfasdfasdfasdf";
String expression = "3";
Pattern p = Pattern.compile(".*3.*");
Matcher m = p.matcher(dummyMessage);
boolean b = m.matches();
if (b) {
System.out.println("MATCH!");
}
else {
System.out.println("NO MATCH!");
}
Or this way:
String dummyMessage = "asdfasdfsadfadfasdf 3 sdfasdfasdfasdf";
String expression = "3"
if (dummyMessage.contains(expression)) {
System.out.println("MATCH!");
}
else {
System.out.println("NO MATCH!");
}
Related
In Java, how would I get a substring of a certain character followed by a number?
The string looks like this:
To be, or not to be. (That is the question.) (243)
I want the substring up until the (243), where the number inside the parenthesis is always changing every time I call.
Use a regular expression:
newstr = str.replaceFirst("\(\d+\)", "");
What this means is to find a substring beginning with (, then any number of digits, and then the character ). Then replace the substring with the empty string, "".
Reference: java.lang.String.replaceFirst()
You could match it with a regex, and get the index of the regex. Then use that to get the index in the string.
An example of that is Can Java String.indexOf() handle a regular expression as a parameter?
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.find()){
System.out.println(matcher.start());//this will give you index
}
You can use String.replaceAll():
String s = "To be, or not to be. (That is the question.) (243)";
String newString = s.replaceAll("\\(\\d+\\).*", "");
I think you can actually just do something like:
mystring.substring(0,mystring.lastIndexOf"("))
assuming that the last thing on the line will be the number in parentheses.
You could use a for loop and add the characters before the number to a separate string
String sentence = "To be, or not to be. (That is the question.) (243)";
public static void main(String[] args) {
String subSentence = getSubsentence(sentence);
}
public String getSubsentence(String sentence) {
String subSentence = "";
boolean checkForNum = false;
for (int i = 0; i < sentence.length(); i++) {
if (checkForNum) {
if (isInteger(sentence.getSubstring(i, i+1))) return subSentence;
checkForNum = false;
} else {
if (sentence.getSubstring(i, i+1).equals("(")) checkForNum = true;
else subSentence += sentence.getSubstring(i, i+1);
}
}
return subSentence;
}
public boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}
Using a regex this can be solved with.
public class RegExParser {
public String getTextPart(String s) {
String pattern = "^(\\D+)(\\s\\(\\d+\\))$";
String part = s.replaceAll(pattern, "$1");
return part;
}
}
Simple and performance is good.
I have this method, which I use to create an array of a conditional expression.
private void convertToList() {
String regex = "[-]?[0-9]+([eE][-]?[0-9]+)?|([-+/*\\\\^])|([()])|(!)|(>=)|(<=)|(<)|(>)|(&&)|(==)|(!=)|([|][|])|(\\[)|(\\])|(and)|(or)|(not)|(true)|(false)|([A-Za-z_][A-Za-z_0-9]*)";
Matcher m3 = Pattern.compile(regex).matcher(this.stringExp);
this.arrayExp = new ArrayList<String>(this.stringExp.length());
while (m3.find()) {
arrayExp.add(m3.group());
}
}
The expression can contain words, numbers and operators (which you can see in the regex).
Now I want to check if the expression is valid before tokenizing. I've tried this, but it doesn't work.
private static void checkString(String s){
String regex = "[-]?[0-9]+([eE][-]?[0-9]+)?|([-+/*\\\\^])|([()])|(!)|(>=)|(<=)|(<)|(>)|(&&)|(==)|(!=)|([|][|])|(\\[)|(\\])|(and)|(or)|(not)|(true)|(false)|([A-Za-z_][A-Za-z_0-9]*)";
Matcher m3 = Pattern.compile(regex).matcher(s);
if (m3.matches()){
System.out.println("OK");
} else {
System.out.println("Not ok");
}
}
Examples of valid strings:
"a + b < 5"
"a <= b && c > 1 || a == 4"
Anyway to do that?
You are probably having problems with spaces. In your example strings are spaces, but they don't match in the regex.
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");
}
}
}
This question already has answers here:
Replace the last part of a string
(11 answers)
Closed 5 years ago.
Is there replaceLast() in Java? I saw there is replaceFirst().
EDIT: If there is not in the SDK, what would be a good implementation?
It could (of course) be done with regex:
public class Test {
public static String replaceLast(String text, String regex, String replacement) {
return text.replaceFirst("(?s)"+regex+"(?!.*?"+regex+")", replacement);
}
public static void main(String[] args) {
System.out.println(replaceLast("foo AB bar AB done", "AB", "--"));
}
}
although a bit cpu-cycle-hungry with the look-aheads, but that will only be an issue when working with very large strings (and many occurrences of the regex being searched for).
A short explanation (in case of the regex being AB):
(?s) # enable dot-all option
A # match the character 'A'
B # match the character 'B'
(?! # start negative look ahead
.*? # match any character and repeat it zero or more times, reluctantly
A # match the character 'A'
B # match the character 'B'
) # end negative look ahead
EDIT
Sorry to wake up an old post. But this is only for non-overlapping instances.
For example .replaceLast("aaabbb", "bb", "xx"); returns "aaaxxb", not "aaabxx"
True, that could be fixed as follows:
public class Test {
public static String replaceLast(String text, String regex, String replacement) {
return text.replaceFirst("(?s)(.*)" + regex, "$1" + replacement);
}
public static void main(String[] args) {
System.out.println(replaceLast("aaabbb", "bb", "xx"));
}
}
If you don't need regex, here's a substring alternative.
public static String replaceLast(String string, String toReplace, String replacement) {
int pos = string.lastIndexOf(toReplace);
if (pos > -1) {
return string.substring(0, pos)
+ replacement
+ string.substring(pos + toReplace.length());
} else {
return string;
}
}
Testcase:
public static void main(String[] args) throws Exception {
System.out.println(replaceLast("foobarfoobar", "foo", "bar")); // foobarbarbar
System.out.println(replaceLast("foobarbarbar", "foo", "bar")); // barbarbarbar
System.out.println(replaceLast("foobarfoobar", "faa", "bar")); // foobarfoobar
}
use replaceAll and add a dollar sign right after your pattern:
replaceAll("pattern$", replacement);
You can combine StringUtils.reverse() with String.replaceFirst()
See for yourself: String
Or is your question actually "How do I implement a replaceLast()?"
Let me attempt an implementation (this should behave pretty much like replaceFirst(), so it should support regexes and backreferences in the replacement String):
public static String replaceLast(String input, String regex, String replacement) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (!matcher.find()) {
return input;
}
int lastMatchStart=0;
do {
lastMatchStart=matcher.start();
} while (matcher.find());
matcher.find(lastMatchStart);
StringBuffer sb = new StringBuffer(input.length());
matcher.appendReplacement(sb, replacement);
matcher.appendTail(sb);
return sb.toString();
}
Use StringUtils from apache:
org.apache.commons.lang.StringUtils.chomp(value, ignoreChar);
No.
You could do reverse / replaceFirst / reverse, but it's a bit expensive.
If the inspected string is so that
myString.endsWith(substringToReplace) == true
you also can do
myString=myString.replaceFirst("(.*)"+myEnd+"$","$1"+replacement)
it is slow, but works:3
import org.apache.commons.lang.StringUtils;
public static String replaceLast(String str, String oldValue, String newValue) {
str = StringUtils.reverse(str);
str = str.replaceFirst(StringUtils.reverse(oldValue), StringUtils.reverse(newValue));
str = StringUtils.reverse(str);
return str;
}
split the haystack by your needle using a lookahead regex and replace the last element of the array, then join them back together :D
String haystack = "haystack haystack haystack";
String lookFor = "hay";
String replaceWith = "wood";
String[] matches = haystack.split("(?=" + lookFor + ")");
matches[matches.length - 1] = matches[matches.length - 1].replace(lookFor, replaceWith);
String brandNew = StringUtils.join(matches);
I also have encountered such a problem, but I use this method:
public static String replaceLast2(String text,String regex,String replacement){
int i = text.length();
int j = regex.length();
if(i<j){
return text;
}
while (i>j&&!(text.substring(i-j, i).equals(regex))) {
i--;
}
if(i<=j&&!(text.substring(i-j, i).equals(regex))){
return text;
}
StringBuilder sb = new StringBuilder();
sb.append(text.substring(0, i-j));
sb.append(replacement);
sb.append(text.substring(i));
return sb.toString();
}
It really works good. Just add your string where u want to replace string in s and in place of "he" place the sub string u want to replace and in place of "mt" place the sub string you want in your new string.
import java.util.Scanner;
public class FindSubStr
{
public static void main(String str[])
{
Scanner on=new Scanner(System.in);
String s=on.nextLine().toLowerCase();
String st1=s.substring(0, s.lastIndexOf("he"));
String st2=s.substring(s.lastIndexOf("he"));
String n=st2.replace("he","mt");
System.out.println(st1+n);
}
}
How do you check if a String contains a special character like:
[,],{,},{,),*,|,:,>,
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("I am a string");
boolean b = m.find();
if (b)
System.out.println("There is a special character in my string");
If you want to have LETTERS, SPECIAL CHARACTERS and NUMBERS in your password with at least 8 digit, then use this code, it is working perfectly
public static boolean Password_Validation(String password)
{
if(password.length()>=8)
{
Pattern letter = Pattern.compile("[a-zA-z]");
Pattern digit = Pattern.compile("[0-9]");
Pattern special = Pattern.compile ("[!##$%&*()_+=|<>?{}\\[\\]~-]");
//Pattern eight = Pattern.compile (".{8}");
Matcher hasLetter = letter.matcher(password);
Matcher hasDigit = digit.matcher(password);
Matcher hasSpecial = special.matcher(password);
return hasLetter.find() && hasDigit.find() && hasSpecial.find();
}
else
return false;
}
You can use the following code to detect special character from string.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DetectSpecial{
public int getSpecialCharacterCount(String s) {
if (s == null || s.trim().isEmpty()) {
System.out.println("Incorrect format of string");
return 0;
}
Pattern p = Pattern.compile("[^A-Za-z0-9]");
Matcher m = p.matcher(s);
// boolean b = m.matches();
boolean b = m.find();
if (b)
System.out.println("There is a special character in my string ");
else
System.out.println("There is no special char.");
return 0;
}
}
If it matches regex [a-zA-Z0-9 ]* then there is not special characters in it.
What do you exactly call "special character" ? If you mean something like "anything that is not alphanumeric" you can use org.apache.commons.lang.StringUtils class (methods IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable).
If it is not so trivial, you can use a regex that defines the exact character list you accept and match the string against it.
This is tested in android 7.0 up to android 10.0 and it works
Use this code to check if string contains special character and numbers:
name = firstname.getText().toString(); //name is the variable that holds the string value
Pattern special= Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Pattern number = Pattern.compile("[0-9]", Pattern.CASE_INSENSITIVE);
Matcher matcher = special.matcher(name);
Matcher matcherNumber = number.matcher(name);
boolean constainsSymbols = matcher.find();
boolean containsNumber = matcherNumber.find();
if(constainsSymbols){
//string contains special symbol/character
}
else if(containsNumber){
//string contains numbers
}
else{
//string doesn't contain special characters or numbers
}
All depends on exactly what you mean by "special". In a regex you can specify
\W to mean non-alpahnumeric
\p{Punct} to mean punctuation characters
I suspect that the latter is what you mean. But if not use a [] list to specify exactly what you want.
Have a look at the java.lang.Character class. It has some test methods and you may find one that fits your needs.
Examples: Character.isSpaceChar(c) or !Character.isJavaLetter(c)
This worked for me:
String s = "string";
if (Pattern.matches("[a-zA-Z]+", s)) {
System.out.println("clear");
} else {
System.out.println("buzz");
}
First you have to exhaustively identify the special characters that you want to check.
Then you can write a regular expression and use
public boolean matches(String regex)
//without using regular expression........
String specialCharacters=" !#$%&'()*+,-./:;<=>?#[]^_`{|}~0123456789";
String name="3_ saroj#";
String str2[]=name.split("");
for (int i=0;i<str2.length;i++)
{
if (specialCharacters.contains(str2[i]))
{
System.out.println("true");
//break;
}
else
System.out.println("false");
}
Pattern p = Pattern.compile("[\\p{Alpha}]*[\\p{Punct}][\\p{Alpha}]*");
Matcher m = p.matcher("Afsff%esfsf098");
boolean b = m.matches();
if (b == true)
System.out.println("There is a sp. character in my string");
else
System.out.println("There is no sp. char.");
//this is updated version of code that i posted
/*
The isValidName Method will check whether the name passed as argument should not contain-
1.null value or space
2.any special character
3.Digits (0-9)
Explanation---
Here str2 is String array variable which stores the the splited string of name that is passed as argument
The count variable will count the number of special character occurs
The method will return true if it satisfy all the condition
*/
public boolean isValidName(String name)
{
String specialCharacters=" !#$%&'()*+,-./:;<=>?#[]^_`{|}~0123456789";
String str2[]=name.split("");
int count=0;
for (int i=0;i<str2.length;i++)
{
if (specialCharacters.contains(str2[i]))
{
count++;
}
}
if (name!=null && count==0 )
{
return true;
}
else
{
return false;
}
}
Visit each character in the string to see if that character is in a blacklist of special characters; this is O(n*m).
The pseudo-code is:
for each char in string:
if char in blacklist:
...
The complexity can be slightly improved by sorting the blacklist so that you can early-exit each check. However, the string find function is probably native code, so this optimisation - which would be in Java byte-code - could well be slower.
in the line String str2[]=name.split(""); give an extra character in Array...
Let me explain by example
"Aditya".split("") would return [, A, d,i,t,y,a] You will have a extra character in your Array...
The "Aditya".split("") does not work as expected by saroj routray you will get an extra character in String => [, A, d,i,t,y,a].
I have modified it,see below code it work as expected
public static boolean isValidName(String inputString) {
String specialCharacters = " !#$%&'()*+,-./:;<=>?#[]^_`{|}~0123456789";
String[] strlCharactersArray = new String[inputString.length()];
for (int i = 0; i < inputString.length(); i++) {
strlCharactersArray[i] = Character
.toString(inputString.charAt(i));
}
//now strlCharactersArray[i]=[A, d, i, t, y, a]
int count = 0;
for (int i = 0; i < strlCharactersArray.length; i++) {
if (specialCharacters.contains( strlCharactersArray[i])) {
count++;
}
}
if (inputString != null && count == 0) {
return true;
} else {
return false;
}
}
Convert the string into char array with all the letters in lower case:
char c[] = str.toLowerCase().toCharArray();
Then you can use Character.isLetterOrDigit(c[index]) to find out which index has special characters.
Use java.util.regex.Pattern class's static method matches(regex, String obj)
regex : characters in lower and upper case & digits between 0-9
String obj : String object you want to check either it contain special character or not.
It returns boolean value true if only contain characters and numbers, otherwise returns boolean value false
Example.
String isin = "12GBIU34RT12";<br>
if(Pattern.matches("[a-zA-Z0-9]+", isin)<br>{<br>
System.out.println("Valid isin");<br>
}else{<br>
System.out.println("Invalid isin");<br>
}