Search a string against another using Regex - java

I need to check whether a String is contained in another String.
For example, "abc" is contained in "abc/def/gh","def/abc/gh" but not in "abcd/xyz/gh","def/abcd/gh".
So, I have split the input String by "/". Then iterated the generated String array to check against the input.
Is it possible to avoid the creation of the array using something like Regex?
Also, could anybody confirm whether using Regex will be faster than the creation & iteration of array as I have used?
Thanks in advance
public class RegexTest {
public static void main(String[] args) {
System.out.println(contains("abc/def/gh", "abc"));
System.out.println(contains("def/abc/gh", "abc"));
System.out.println(contains("def/abcd/gh", "abc"));
System.out.println(contains("abcd/xyz/gh", "abc"));
}
private static boolean contains(String input, String searchString) {
String[] strings = input.split("/");
for (String string : strings) {
if (string.equals(searchString))
return true;
}
return false;
}
}
The console output is:
true
true
false
false

Something like this:
String pattern = "(.*/)?abc(/.*)?";
System.out.println("abc/def/gh".matches(pattern));
System.out.println("def/abc/gh".matches(pattern));
System.out.println("def/abcd/gh".matches(pattern));
System.out.println("abcd/xyz/gh".matches(pattern));
prints
true
true
false
false

Using regex is more convenient (?), but please time yourself whether it is faster:
if (!searchString.contains("/")) {
return input.matches("(.*/)?" + Pattern.quote(searchString) + "(/.*)?");
} else {
return false;
}
I made sure that the searchString does not contain /, before inserting it as literal with Pattern.quote. The regex will make sure that there is a / before and after the search string in the input, either that or the search string is the first or last token in the input.

try this regex
s.matches("^abc/.+|.+/abc/.+|.+/abc$")
or
s.startsWith("abc/") || s.contains("/abc/") || s.endsWith("/abc")

Related

How to remove every sequence of "()" in a string in java?

I'm trying to remove every sequence of () in my string.
For example my String is:
String a = "() a)";
And I want it to become
" a)"
When I tried this it gave me an infinite loop
public static String removeParentheses(String s) {
while (s.contains("()")) {
s = s.replaceAll("()", "");
}
return s;
}
String replaceAll method require regexp in parameter. In your case you provide empty group. To use string as parameter you can use replace method like:
public static void main(String[] args) {
String toChange = "asa()assaa()ass()asa()";
String result = toChange.replace("()", "");
assert Objects.equals(result, "asaassaaassasax");
}
Or change the regexp to correct form using \ character in way:
public static void main(String[] args) {
String toChange = "asa()assaa()ass()asa()";
String result = toChange.replaceAll("\\(\\)", "");
assert Objects.equals(result, "asaassaaassasax");
}
According the documentation of String.replaceAll, the first argument is a regular expression.
This means () is not being treated literally, it's being treated as an empty capture group, which effectively matches nothing. I think what you're looking for is the normal String.replace method. I'm aware that the names of these methods seem to imply that replace only replaces one instance while replaceAll replaces all of them, but this is not the case.
public static String removeParentheses(String s) {
return s.replace("()", "");
}
JDoodle deomonstrating code above
If for some reason you would like to continue using replaceAll instead, you can dynamically escape the pattern using Pattern.quote.
public static String removeParentheses(String s) {
String pattern = Pattern.quote("()");
return s.replaceAll(pattern, "");
}
JDoodle demonstrating code above

Split method creates empty elements in Java Array

I have the following String "Make Me A SandWich"
Someone decided to troll me and replace the spaces with a random number of LOL.
so now the string is "LOLMakeLOLLOLLOLMELOLALOLSandWich"
My goal is to revert this change.
I tried to create a string array with split method but this caused "empty" elements inside of the array that has a value but when I try to log it, it doesn't show anything. It's also not equal to ""
Public class MyClass{
public static void main(String[] args) {
String trollText = "MakeLOLLOLLOLMELOLALOLSandWich";
String[] array = trollText.split("LOL");
if (array[1]=="")System.out.print("it's an empty string");
if (array[1]==" ")System.out.print("it's a space sign");
if (array[1]==null)System.out.print("it's equal to nothing");
if (array[1]==' '+"")System.out.print("I don't know what's that");
else System.out.print(array[1]+"<-- This is an element and it has a value");
}
}
I consider the problem solved if someone tells me what array[1] equals to.
Knowing the value will give me something to compare to when copying the elements into a new array.
When comparing two strings in java, you cannot use == operator which compares object references. You need to use array[1].equals("")
Also, if you simply want to replace all occurrences of a string, you can do following
trollText.replaceAll("LOL", " ")
Here is my solution. skipping empty or " " string and appending notEmpty values to new StringBuilder() and finally print it.
import java.util.Arrays;
public class LOL_problem {
public static void main(String[] args) {
String trollText = "MakeLOLLOLLOLMELOLALOLSandWich";
StringBuilder sb = new StringBuilder();
String[] array = trollText.split("LOL");
//System.out.println(Arrays.toString(array));
for (String str : array) {
if (!str.equals("")) sb.append(str+" ");
}
System.out.println(sb.toString().trim());
}
}
We should use equals(String str) method to check if strings are equals instead of '==' which does object reference check.
To replace all the occurrence, you can use trollText.replaceAll method as below.
public class MyClass{
public static void main(String[] args) {
String trollText = "MakeLOLLOLLOLMELOLALOLSandWich";
String result = trollText.replaceAll("LOL", " ");
System.out.println(result);
}
}
To compare Strings in Java, use:
String.equals("text");
This will return true if the Strings are identical and false if not.

Java: Validating a string

So I am working on a project in java and I have just a quick question.
I have a method that is receiving a string and I want to strip out the spaces and check that is is not empty. So far I have the below in place however it doesn't seem to be working properly.
public static Boolean isValid(String s) {
s.replace(" ", "");
if (s == ""){
return false;
}
else {
return true;
}
}
Any help would be appreciated :)
Ta
You can try with this:
public static Boolean isValid(String s) {
return (!s.trim().isEmpty());
}
First you have forgot the assignment for s.replace(" ",""). Store that in a variable, e.g.
x = s.replace(" ","");
For string comparison use .equals() method instead of ==
You can use the following code as well :
newString=myString.replaceAll("\\s+","");
This removes one or more spaces in between Strings as well as leading and trailing whitespaces
Use : myString.trim() to remove only leading and trailing whitespaces
and then newString.isEmpty()
You should use .equals() to compare Strings
When you're comparing strings, use .equals().
Its only in artihmetic expressions you use the == sign
TO check whether your string is empty use the .isEmpty() function
You forgot the assignment:
s = s.replace(" ", "");
EDIT:
for the comments stating that == is not working. I wanted to say that it does work for Java 7
replaceAll() method supports regular expressions as well as isEmpty() is already there in String class so we can reuse it and is safer to use here.
simply use like this:
public static Boolean isValid(String s) {
s = s.replaceAll("\\s", "");
if (s.isEmpty()) {
return false;
}
else {
return true;
}
}
Difference between equals and == incase of String comparison is well explained in the thread
value of s.replace() should be assigned to itself or some other variable.

Get the Smallest Matching String from a Long String

Suppose I have a String
interpreter, interprete, interpret
now what i want to do is to get the smallest matching string from the above string that must be:
interpret
Is it possible using Java if it is can somebody help me out digging this problem thanks
Check out this.....
public static void main(String[] ar)
{
List<String> all=new LinkedList<String>();
all.add("interpreter");
all.add("interprete");
all.add("interpret");
String small="";
small=all.get(0);
for (String string : all) {
if(small.contains(string))
{
small=string;
}
}
System.out.println(small);
}
Let me know, Is it satisfying your requirement???
//-----------------Edited One--------------------------
public static void main(String[] ar)
{
List<String> all=new LinkedList<String>();
Set<String> result=new LinkedHashSet<String>();
all.add("interpreter");
all.add("interprete");
all.add("interpret");
all.add("developed");
all.add("develops");
String small="";
for(int i=0;i<all.size();i++)
{
small=all.get(i);
for(int j=i;j<all.size();j++)
{
if(small.contains(all.get(j)))
{
small=all.get(j);
}
}
result.add(small);
}
for (String string : result) {
System.out.println(string);
}
}
If I get you correctly, you want the shortest word in an input string s which includes a target string t="interpret".
So first, split the string into words w, e.g., using s.split("\\s*,\\s*"), then use w.contains(t) on each string w to check if it contains the word you look for. Choose the shortest string for which the contains method returns true.
you need to compare all char one by one of all string and a array of boolean flag maintain
for every pair of string then check out all Boolean array similarity(length) and then substring
of any string from that length
i hope this will help
What you are looking for is called a lemmatizer/steamer for Java.
There are a few of them (I have not used any) but you may want to search/try a few of them:
Snowball
Lemamatization
You should test each of them, because for example some (in case of snowball) will do:
Community
Communities --> Communiti // this is obviously wrong

I need to check the occurrence of a particular symbol at the beginning of my String

I need to check the occurrence of a particular symbol say #$ at the beginning of my String.
Simply, I need to get the
boolean symbolExist true for all the following cases,
#$MyString
#$<Space>myString
#$<Space><Space>myString
#$<Space><space>my#$String
#$My#$String
etc. (never mind what ever coming after the 2 characters)
boolean symbolExist false for
MyString#$
My#$string
etc .
You can use the startsWith method of String class:
String s = "#$test";
System.out.println(s.startsWith("#$"));
the output is true.
In String Class we have one called boolean startsWith(String prefix) using this method you can solve your problem.
String content = "#$MyString";
if(content.startsWith("#$")) //This will return true if String starts with "#$"
{
}
try this :
boolean symbolExists ;
String myString;
if(myString.startsWith("#$"))
symbolExists = true;
else
symbolExists = false;

Categories

Resources