I'm getting the URL(http://localhost:8080/CompanyServices/api/creators/2173) shown below from a HTTP Response header and I want to get the id after the creators which is 2173.
So, I deleted all non digits as shown below and got the following result : 80802173.
Is it a good approach to get the last 4 digits from the above set of digits?
One thing is that, this part localhost:8080 could change depending upon the server I deploy my application so I'm wondering if I should just grab something after creators/ ? If yes, then what is the best way to go about it?
public class GetLastFourIDs {
public static void main(String args[]){
String str = "http://localhost:8080/CompanyServices/api/creators/2173";
String replaceString=str.replaceAll("\\D+","");
System.out.println(replaceString);
}
}
You can use regex API e.g.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "http://localhost:8080/CompanyServices/api/creators/2173";
Pattern pattern = Pattern.compile("(creators/\\d+)");
Matcher matcher = pattern.matcher(str);
int value = 0;
if (matcher.find()) {
// Get e.g. `creators/2173` and split it on `/` then parse the second value to int
value = Integer.parseInt(matcher.group().split("/")[1]);
}
System.out.println(value);
}
}
Output:
2173
Non-regex solution:
public class Main {
public static void main(String[] args) {
String str = "http://localhost:8080/CompanyServices/api/creators/2173";
int index = str.indexOf("creators/");
int value = 0;
if (index != -1) {
value = Integer.parseInt(str.substring(index + "creators/".length()));
}
System.out.println(value);
}
}
Output:
2173
[Update]
Incorporating comment by Andreas as follows:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "http://localhost:8080/CompanyServices/api/creators/2173";
Pattern pattern = Pattern.compile("creators/(\\d+)");
Matcher matcher = pattern.matcher(str);
int value = 0;
if (matcher.find()) {
value = Integer.parseInt(matcher.group(1));
}
System.out.println(value);
}
}
Output:
2173
Related
Refer to the test below, some test cases are failed in fact even the output is correct. Can anyone advise?
https://coderbyte.com/editor/Longest%20Word:Java
Longest Word
Have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty.
Examples
Input: "fun&!! time"
Output: time
Input: "I love dogs"
Output: love
Below are the invalid failing test cases
For input "a beautiful sentence^&!" the output was incorrect. The correct output is beautiful
For input "oxford press" the output was incorrect. The correct output is oxford
For input "123456789 98765432" the output was incorrect. The correct output is 123456789
For input "a b c dee" the output was incorrect. The correct output is dee
For input "a confusing /:sentence:/[ this is not!!!!!!!~" the output was incorrect. The correct output is confusing
The program
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
public static final String REG_EXP_CHAR_ONLY = "(?=.*?[a-zA-Z0-9 ])";
public static String LongestWord(String sen) {
StringBuffer strBuffer = new StringBuffer();
for (String c : sen.split("")) {
//System.out.println("c--------->" + c);
if (isValid(c)) {
strBuffer.append(c);
}
}
//System.out.println(strBuffer.toString());
String longest = Arrays.stream(strBuffer.toString().split(" ")).max(Comparator.comparingInt(String::length))
.orElse(null);
return longest;
}
public static boolean isValid(String c) {
// System.out.println("char -->" + c);
Pattern pattern = Pattern.compile(REG_EXP_CHAR_ONLY);
Matcher matcher = pattern.matcher(c);
boolean matchFound = matcher.find();
if (matchFound) {
// System.out.println("Match found");
return true;
}
return false;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LongestWord(s.nextLine()));
}
}
It seems that this is a problem from coderbyte. I copied your code and submitted. Then it passed.
==================================================================
Edit:
maybe you should use "StringBuilder"(not StringBuffer) instead.
I just fixed all warnings in ide and then all tests pass.
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
public static final String REG_EXP_CHAR_ONLY = "(?=.*?[a-zA-Z0-9 ])";
public static String LongestWord(String sen) {
StringBuilder strBuffer = new StringBuilder();
for (String c : sen.split("")) {
//System.out.println("c--------->" + c);
if (isValid(c)) {
strBuffer.append(c);
}
}
return Arrays.stream(strBuffer.toString().split(" ")).max(Comparator.comparingInt(String::length))
.orElse(null);
}
public static boolean isValid(String c) {
// System.out.println("char -->" + c);
Pattern pattern = Pattern.compile(REG_EXP_CHAR_ONLY);
Matcher matcher = pattern.matcher(c);
// System.out.println("Match found");
return matcher.find();
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LongestWord(s.nextLine()));
}
}
I'm trying to return a string of regular expression matches. Specifically, trying to return all vowels (aeiou) found in a string. The following code returns the 2 oo's but not the e.
Expecting: eoo
Getting: oo
Why is it not finding and appending the e to the StringBuilder object? Thank you.
import java.lang.StringBuilder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
String inp = "Hello World!";
System.out.println(vowelOnly(inp));
}
public static String vowelOnly(String input) {
Pattern vowelPattern = Pattern.compile("[aeiou]+");
Matcher vowelMatcher = vowelPattern.matcher(input);
StringBuilder sb = new StringBuilder();
int i = 0;
if (vowelMatcher.find()) {
while (vowelMatcher.find( )) {
sb.append(vowelMatcher.group());
i++;
}
return sb.toString();
} else {
return "No matches";
}
}
}
When you call vowelMatcher.find() inside your if condition, you tell the matcher to find the first string matching the specified pattern. In this case, it is "e". When you call it again in your while condition, the matcher finds the next match, in this case it is "o".
From there, it loops through the rest of the String. If you gave it the input "Hello World eeee", it would return "ooeeee", since you always discard the first match by calling .find() without calling .group() immediately after.
Change your loop to be like this, and it should work:
int i = 0;
while (vowelMatcher.find()) {
sb.append(vowelMatcher.group());
i++;
}
return i == 0 ? "No matches" : sb.toString(); // return "no matches" if i is 0, otherwise, string
Your first call to vowelMatcher.find() in the if statement finds the "e" and the subsequent calls to vowelMatcher.find() in the while loop find all subsequent vowels.
Thats what you need:
public static void main(String[] args) {
String inp = "Hello World!";
System.out.println(vowelOnly(inp));
}
public static String vowelOnly(String input) {
Pattern vowelPattern = Pattern.compile("[aeiou]+");
Matcher vowelMatcher = vowelPattern.matcher(input);
StringBuilder sb = new StringBuilder();
int i = 0;
while (vowelMatcher.find()) {
sb.append(vowelMatcher.group());
i++;
}
return i == 0 ? "No matches" : sb.toString();
}
That would probably be the solution you're looking for:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String inp = "Hello World!";
System.out.println(vowelOnly(inp));
}
public static String vowelOnly(String input) {
Pattern vowelPattern = Pattern.compile("[aeiou]+");
Matcher vowelMatcher = vowelPattern.matcher(input);
StringBuilder sb = new StringBuilder();
while (vowelMatcher.find()) {
sb.append(vowelMatcher.group());
}
if (sb.length() == 0) {
return "No matches";
}
return sb.toString();
}
}
Couple of notes:
You don't need to import java.lang.* classes.
With the matcher, whatever you find, you should group it immediately to collect.
You don't need the iteration variable. StringBuilder.length() would simply reveal if it's empty.
In this code, we remove the substring "luna" from email string using the .replaceFirst method. We are removing the characters in between + and #. But this happens only in the first instance because we used .replaceFirst. What if we wanted to target the second instance of + and # to remove "smith"?
Our output now is alice+#john+smith#steve+oliver# but we want alice+luna#john+#steve+oliver#
public class Main {
public static void main(String[] args) {
String email = "alice+luna#john+smith#steve+oliver#";
String newEmail = email.replaceFirst("\\+.*?#", "");
System.out.println(newEmail);
}
}
You can find the second + like so:
int firstPlus = email.indexOf('+');
int secondPlus = email.indexOf('+', firstPlus + 1);
(You need to handle the case that there aren't two +s to find, if necessary).
Then find the following #:
int at = email.indexOf('#', secondPlus);
Then stitch it back together:
String newEmail = email.substring(0, secondPlus + 1) + email.substring(at);
or
String newEmail2 = new StringBuilder(email).delete(secondPlus + 1, at).toString();
Ideone demo
Unfortunately Java doesn't have methods like replace second, replace third etc. You can either replaceAll (which will replace all occurences) OR invoce replaceFirst again on the already replaced string. That's basically replacing the second. If you want to replace ONLY the second - then you can do it with substrings or do a regex matcher and iterate on results.
public static void main(String[] args) {
String email = "alice+luna#john+smith#steve+oliver#";
String newEmail = email.replaceFirst("\\+.*?#", "");
newEmail = newEmail .replaceFirst("\\+.*?#", ""); //this replaces the second right? :)
newEmail = newEmail .replaceFirst("\\+.*?#", ""); // replace 3rd etc.
System.out.println(newEmail);
}
You can alternate value of parameter n in following replaceNth method to 2, 3 to perform exactly the same operation as that of replaceSecond or replaceThird. ( Note: this method can be applied in any other value of n. If nth pattern do not exist , it simply return given string ).
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static String replaceNth(String str, int n, String regex, String replaceWith) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
n--;
if (n == 0) {
return str.substring(0,m.start() + 1)+ replaceWith + str.substring(m.end() - 1);
}
}
return str;
}
public static void main(String args[]) {
String email = "alice+luna#john+smith#steve+oliver#";
System.out.println(replaceNth(email, 2, "\\+.*?#", ""));
}
}
I think it is better to encapsulate this logic into separate method, where String and group position are arguments.
private static final Pattern PATTERN = Pattern.compile("([^+#]+)#");
private static String removeSubstringGroup(String str, int pos) {
Matcher matcher = PATTERN.matcher(str);
while (matcher.find()) {
if (pos-- == 0)
return str.substring(0, matcher.start()) + str.substring(matcher.end() - 1);
}
return str;
}
Additionally, you can add more methods, to simplify using this util; like removeFirst() or removeLast()
public static String removeFirst(String str) {
return removeSubstringGroup(str, 0);
}
public static String removeSecond(String str) {
return removeSubstringGroup(str, 1);
}
Demo:
String email = "alice+luna#john+smith#steve+oliver#";
System.out.println(email);
System.out.println(removeFirst(email));
System.out.println(removeSecond(email));
System.out.println(removeSubstringGroup(email, 2));
System.out.println(removeSubstringGroup(email, 3));
Output:
alice+luna#john+smith#steve+oliver#
alice+#john+smith#steve+oliver#
alice+luna#john+#steve+oliver#
alice+luna#john+smith#steve+#
alice+luna#john+smith#steve+oliver#
Ideone demo
Suppose i have a string "[cat]:|:[]:|:[dog]:|:[cow]:|:[]:|:[]:|:[monkey]" like this.
I am able to print [cat][dog][cow][monkey] from the above string.
How can i print something like this = [cat]:|:[dog]:|:[cow]:|:[monkey].
please help.
import java.util.regex.*;
public class RegexMain {
static final String PATTERN = "\\[([^]]+)\\]|\"[^\"]*\"";
static final Pattern CONTENT = Pattern.compile(PATTERN);
public static void main(String[] args) {
String test1 = "[cat] [] [dog] [cow] [] [] [monkey]";
Matcher match = CONTENT.matcher(test1);
while(match.find()) {
if(match.group(1).length() != 0) {
System.out.print( match.group().trim());
}
}
}
}
I am actually not sure what your string is exactly (you are using different ones in your explanation and code). Anyways you can try this :
public static void main(String[] args) {
String s = "[cat]:|:[]:|:[dog]:|:[cow]:|:[]:|:[]:|:[monkey]";
System.out.println(s.replaceAll(":\\[\\]:\\|", ""));
}
O/P :
[cat]:|:[dog]:|:[cow]:|:[monkey]
how about
System.out.print( match.group().trim() + ":|:");
Hey guys am hoping you could help me with this.
Am trying to get all the integers from this code, just leaving the letters behind and am seriously lost here
public class Tie {
public static void main(String agrs[]){
String fr = "4544FF";
int yu = fr.length();
System.out.print(yu);
}
}
If you only seek to remove the numeric digits from the string, use regex and replace, with regex 'd' you can filter on all digits.
String fr = "4544FF";
fr = fr.replaceAll("\\d","");
//result should be that fr now is contains only "FF", because the digits have bee replaced with nothing.
I haven't tested it, but it should work, if my little experience with regex serves me right.
What you can do is use this method substring(int start, int final).
public static void main(String agrs[]){
String fr = "4544FF";
String numbers= fr.substring(0, 4);
String letters= fr.substring(4);
System.out.println("It will shows 4544" + numbers);
System.out.println("It will shows FF" + letters);
int convertNumber = Integer.parseInt(numbers); //Convert to int
System.out.println("" +convertNumber);
}
It will show you only the numbers 4544.
I hope that solve your problem.
try this code
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tie {
public static void main(String agrs[]){
Tie tie = new Tie();
String fr = "4544FF";
char[] strings = fr.toCharArray();
List<Integer>integers = new ArrayList<Integer>();
for(int i=0;i<strings.length;i++){
if(tie.validationNumber(strings[i]+"")){
integers.add(Integer.parseInt(strings[i]+""));
}
}
for(Integer i:integers){
System.out.println(i);
}
}
public boolean validationNumber(String s){
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(s);
if (matcher.matches()) {
return true;
}
return false;
}
}