How to use Pattern.compile with spaces in Java? - java

I have a problem with matching the two words with a space between them in Pattern.compile in Java.
My string is "What is your name?".
My code:
String namee = "What is your name?";
Pattern pattern = Pattern.compile("What is|Address is");
if (pattern.matcher(namee).find())
{
if (namee.equals("What is"))
{
namee = "name";
}
}
what I am trying to achieve if a string consist "What is" then the string itself should change to "name". But its not wotking with space...

Solution1
You can use Matcher and then check with the matcher.group() like this:
Pattern pattern = Pattern.compile("What is|Address is");
Matcher matcher = pattern.matcher(namee);
if (matcher.find()) {
if (matcher.group().equals("What is")) {
namee = "name";
}
}
Solution2
If you want to check if your string contain What is or Address is, then you can easily use :
if(namee.contains("What is")){
namee = "What is";
}else if (namee.contains("Address is")){
namee = "....";
}
Solution3
If you want to check if your string start with What is or Address is then you can use :
if(namee.startsWith("What is")){
namee = "What is";
}else if (namee.startsWith("Address is")){
namee = "....";
}

Try like this (to be safe; better code readability as well IMHO):
Pattern pattern = Pattern.compile("(What is)|(Address is)")
but the following code feels wrong:
if (namee.equals("What is"))
...
you probably want to use instead the java.util.regex.Matcher you just created. For instance:
Matcher matcher = pattern.matcher(namee);
if (matcher.find()) {
if (matcher.group().equals("What is")) {
...
}
}

Related

How can i extract substring from the string using regex in Java?

I have a String xxxxxxxxsrc="/slm/attachment/63338424306/Note.jpg"xxxxxxxx Now, I want to extract substrings slm/attachment/63338424306/Note.jpg & Note.jpg from the String in to variables i.e. temp1 & temp2.
How can I do that using regex in Java?
Note: 63338424306 could be any random no. & Note.jpg could be anything
like Note.png or abc.jpg or xxxx.yyy etc.
Please help me to extract these two strings using regex.
You can use negative look behind to get file name
((?:.(?<!/))+)\"
and below regex to get full path
/(.*)\"
Sample code
public static void main(String[] args) {
Pattern pattern = Pattern.compile("/(.*)\"");
Pattern pattern1 = Pattern.compile("((?:.(?<!/))+)\"");
String matchString = "/slm/attachment/63338424306/Note.jpg\"xxxxxxxx";
Matcher matcher = pattern.matcher(matchString);
String fullString = "";
while (matcher.find()) {
fullString = matcher.group(1);
}
matcher = pattern1.matcher(matchString);
String fileName = "";
while (matcher.find()) {
fileName = matcher.group(1);
}
System.out.println(fullString + " " + fileName);
}
As per your comment taking the string as declared below in my code:
Please clarify if your input string is not like this or I'm missing something.
public static void main(String[] args) {
String str = "xxxxxxxxsrc=\"/slm/attachment/63338424306/Note.jpg\"xxxxxxxx";
String url = null;
// The below pattern will grab string between quotes
Pattern p = Pattern.compile("\"([^\"]*)\"");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group(1));
url = m.group(1);
}
// and this will grab filename from the path(url)
p = Pattern.compile("(?:.(?<!/))+$");
m = p.matcher(url);
while (m.find()) {
System.out.println(m.group());
}
}

Match everything after and before something regex Java

Here is my code:
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern p = Pattern.compile("(?<=.com\\/excludethis).*\\/"); //search for this pattern
Matcher m = p.matcher(stringToSearch); //match pattern in StringToSearch
String store= "";
// print match and store match in String Store
if (m.find())
{
String theGroup = m.group(0);
System.out.format("'%s'\n", theGroup);
store = theGroup;
}
//repeat the process
Pattern p1 = Pattern.compile("(.*)[^\\/]");
Matcher m1 = p1.matcher(store);
if (m1.find())
{
String theGroup = m1.group(0);
System.out.format("'%s'\n", theGroup);
}
I want to to match everything that is after excludethis and before a / that comes after.
With "(?<=.com\\/excludethis).*\\/" regex I will match 123456/ and store that in String store. After that with "(.*)[^\\/]" I will exclude / and get 123456.
Can I do this in one line, i.e combine these two regex? I can't figure out how to combine them.
Just like you have used a positive look behind, you can use a positive look ahead and change your regex to this,
(?<=.com/excludethis).*(?=/)
Also, in Java you don't need to escape /
Your modified code,
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern p = Pattern.compile("(?<=.com/excludethis).*(?=/)"); // search for this pattern
Matcher m = p.matcher(stringToSearch); // match pattern in StringToSearch
String store = "";
// print match and store match in String Store
if (m.find()) {
String theGroup = m.group(0);
System.out.format("'%s'\n", theGroup);
store = theGroup;
}
System.out.println("Store: " + store);
Prints,
'123456'
Store: 123456
Like you wanted to capture the value.
This may be useful for you :)
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern pattern = Pattern.compile("excludethis([\\d\\D]+?)/");
Matcher matcher = pattern.matcher(stringToSearch);
if (matcher.find()) {
String result = matcher.group(1);
System.out.println(result);
}
If you don't want to use regex, you could just try with String::substring*
String stringToSearch = "https://example.com/excludethis123456/moretext";
String exclusion = "excludethis";
System.out.println(stringToSearch.substring(stringToSearch.indexOf(exclusion)).substring(exclusion.length(), stringToSearch.substring(stringToSearch.indexOf(exclusion)).indexOf("/")));
Output:
123456
* Definitely don't actually use this

How can i replace this?

How can I replace this
String str = "KMMH12DE1433";
String pattern = "^[a-z]{2}([0-9]{2})[a-z]{1,2}([0-9]{4})$";
String str2 = str.replaceAll(pattern, "repl");
Log.e("Founded_words2",str2);
What I got: KMMH12DE1433
What I want: MH12DE1433
Try it like this using a proper java.util.regex.Pattern and a java.util.regex.Matcher:
String str = "KMMH12DE1433";
//Make the pattern, case-insensitive using (?i)
Pattern pattern = Pattern.compile("(?i)[a-z]{2}([0-9]{2})[a-z]{1,2}([0-9]{4})");
//Create the Matcher
Matcher m = pattern.matcher(str);
//Check if we find anything
if(m.find()) {
//Use what you found - with proper capturing groups you
//gain access to parts of your pattern as needed
System.out.println("Found this: " + m.group());
}
If you just want to remove the first two characters and if the first two characters will always be uppercase letters:
String str = "KMMH12DE1433";
String pattern = "^[A-Z]{2}";
String str2 = str.replaceAll(pattern, "");
Log.e("Output string: ", str2);
try this :
String a = "KMMH12DE1433";
String pattern = "^[A-Z]{2}";
String rs = a.replaceAll(pattern,"");
Please change like this
String ans=str.substring(0);

how can I get particular string(sub string ) from a string

I have string like
{Action}{RequestId}{Custom_21_addtion}{custom_22_substration}
{Imapact}{assest}{custom_23_multiplication}.
From this I want only those sub string which contains "custom".
For example from above string I want only
{Custom_21_addtion}{custom_22_substration}{custom_23_multiplication}.
How can I get this?
You can use a regular expression, looking from {custom to }. It will look like this:
Pattern pattern = Pattern.compile("\\{custom.*?\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputString);
while (matcher.find()) {
System.out.print(matcher.group());
}
The .* after custom means 0 or more characters after the word "custom", and the question mark limits the regex to as few character as possible, meaning that it will break on the next } that it can find.
If you want an alternative solution without regex:
String a = "{Action}{RequestId}{Custom_21_addtion}{custom_22_substration}{Imapact}{assest}{custom_23_multiplication}";
String[] b = a.split("}");
StringBuilder result = new StringBuilder();
for(String c : b) {
// if you want case sensitivity, drop the toLowerCase()
if(c.toLowerCase().contains("custom"))
result.append(c).append("}");
}
System.out.println(result.toString());
you can do it sth like this:
StringTokenizer st = new StringTokenizer(yourString, "{");
List<String> llista = new ArrayList<String>():
Pattern pattern = Pattern.compile("(\W|^)custom(\W|$)", Pattern.CASE_INSENSITIVE);
while(st.hasMoreTokens()) {
String string = st.nextElement();
Matcher matcher = pattern.matcher(string);
if(matcher.find()){
llista.add(string);
}
}
Another solution:
String inputString = "{Action}{RequestId}{Custom}{Custom_21_addtion}{custom_22_substration}{Imapact}{assest}" ;
String strTokens[] = inputString.split("\\}");
for(String str: strTokens){
Pattern pattern = Pattern.compile( "custom", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputString);
if (matcher.find()) {
System.out.println("Tag Name:" + str.replace("{",""));
}
}

Removing link from Text in Java?

I need to change somethign like this -> Hello, go here http://www.google.com for your ...
grab the link, and change it in a method i made, and replace it back into the string like this
-> Hello, go here http://www.yahoo.com for your...
Here is what i have so far:
if(Text.toLowerCase().contains("http://"))
{
// Do stuff
}
else if(Text.toLowerCase().contains("https://"))
{
// Do stuff
}
All i need to do is change the URL in the String to something different. The Url in the String will not always be http://www.google.com, so i can not just say replace("http://www.google.com","")
Use regex:
String oldUrl = text.replaceAll(".*(https?://)www((\\.\\w+)+).*", "www$2");
text = text.replaceAll("(https?://)www(\\.\\w+)+", "$1" + traslateUrl(oldUrl));
Note: code changed to meet extra requirements in comments below.
you can grab the link from the string using below code. I assumed the string will contain only .com domain
String input = "Hello, go here http://www.google.com";
Pattern pattern = Pattern.compile("http[s]{0,1}://www.[a-z-]*.com");
Matcher m = pattern.matcher(input);
while (m.find()) {
String str = m.group();
}
Have you tried something like:
s= s.replaceFirst("http:.+[ ]", new link);
This will find any word beginning with http up till the first white space and replace it with whatever you want
if you want to keep the link then you can do:
String oldURL;
if (s.contains("http")) {
String[] words = s.split(" ");
for (String word: words) {
if (word.contains("http")) {
oldURL = word;
break;
}
}
//then replace the url or whatever
}
You can try this
private String removeUrl(String commentstr)
{
String urlPattern = "((https?|ftp|gopher|telnet|file|Unsure|http):((//)|(\\\\))+[\\w\\d:##%/;$()~_?\\+-=\\\\\\.&]*)";
Pattern p = Pattern.compile(urlPattern,Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(commentstr);
int i = 0;
while (m.find()) {
commentstr = commentstr.replaceAll(m.group(i),"").trim();
i++;
}
return commentstr;
}

Categories