Java - Find occurrences of substring in a string [duplicate] - java

This question already has answers here:
Find the Number of Occurrences of a Substring in a String
(27 answers)
Closed 5 years ago.
Say I had a string
String s = "foofoo bar barbarbar foo
and I wanted to find all the occurrences of foo and print them out like so:
foo foo foo
I've already looked into StringUtils, but it seems to me (an amateur) that this library is only able to count the number of occurrences of foo. Is there something I'm doing wrong here? Or is regex really the best way to go?

You can use indexOf method of String class and substring method of the same class to achieve the desired result, but using regex it would be less typing and easier to implement. I have provided a possible solution for you below
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Sample {
public static void main(String[] args) {
String s = "foofoo bar barbarbar foo";
Pattern p = Pattern.compile("foo");
Matcher m = p.matcher(s);
while(m.find()){
System.out.print(m.group() + " ");
}
}
}

Related

Finding the any number of characters between brackets using regex? [duplicate]

This question already has answers here:
Print regex matches in java
(2 answers)
Closed 3 years ago.
I've been struggling with some regex parsing to get a particular substring out of a string. I want to get the {0} out of a string. The caveat is that the substring can have any number of 0'
s within the {} and there can be many instances of {0} in the String. A few example inputs are:
{0} should print {0}
F-{000} print {000}
F-{00000000}-{0000} print {00000000} & {0000}
Here is the code I have:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main
{
public static void main(String[] args) {
String displayFormat = "A-{0000}";
printValue("^\\{[0]+}$", displayFormat); // this searches for a string beginning with {, ends with }, and has 1 or more instances of 0 in it
printValue("\\{[0]+\\}", displayFormat); // same as above but without the strict requirement of beginning and ending with {}, rather looks for the literal {}
}
public static void printValue(String regex, String displayFormat) {
final Matcher matcher = Pattern.compile(regex).matcher(displayFormat);
String zeroSection = null;
while(matcher.find()) {
if(matcher.groupCount() > 0) {
System.out.println("Group: " + matcher.group(1));
}
}
}
}
Any help would be appreciated. Thanks!
I was able to find the correct regex. The regex that was posted in the answer above seems to work, but I guess the issue was more around how I was printing the string. I should have been printing group(0) instead of group(1). Silly mistake.

JAVA Regex - How do I filter out entire strings with lengths that are greater than a certain number? [duplicate]

This question already has answers here:
Difference between matches() and find() in Java Regex
(5 answers)
Closed 3 years ago.
My program is used to filter out names starting with a capital letter [A-M] and to filter out any names with a length less than 5 and greater than 9. The code does filter out the names with a length less than 5, but when I input a name with a length greater than 9, it just cuts off the rest of the name.
Ex: Bartholomew would cut off to Bartholom rather than just not using Bartholomew.
I have tried to move the length flag to different spots in the regex field. Other than that, I do not know regex well enough to try much more. As for putting these strings into another function just to test the lengths - I am trying to make it in one regex field.
import java.io.File;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Egor {
public static void main(String args[]) throws Exception{
Scanner s = new Scanner(new File("Names.dat"));
String[] names = new String[30];
int i = 0;
while(s.hasNext()) {
names[i] = s.next();
i++;
}
String store = "";
for (String str: names) {
store = store + str + " ";
}
System.out.println(store);
Pattern checkName = Pattern.compile("([A-M][a-z]{5,9})");
Matcher matcher = checkName.matcher(store);
System.out.println("-----------------------");
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
The expected should print out names like - Ashley, Brendan, Henry would print out
The unexpected is that names like - Bartholomew, with lengths greater than 9 print out to Bartholom
You need to add a positive look behind and positive look ahead and positive look behind for the desired characters that separate your names. Based on your code it looks like that would be a start of string anchor or space, and a end of string anchor or space for the look behind and look ahead respectively. Will look something like this:
(?<=\b)([A-M][a-z]{5,9})(?=\b)
Look ahead and look behinds in regex match what is ahead of and behind, but do not include it in the matched result.

Regex for Delimeter [duplicate]

This question already has answers here:
Is it possible to match nested brackets with a regex without using recursion or balancing groups?
(2 answers)
Closed 5 years ago.
I am trying to write a regex for delimiters “(“, “)”, “,”. I tried to write a regex but it is not the correct for the delimeters.
Let's say the input is mult(3,add(2,subs(4,3))). The output with my delimeter regex is: 3,add(2,subs(4,3.
public class Practice {
private static final String DELIMETER = "\\((.*?)\\)";
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
String arg = reader.next();
Pattern p = Pattern.compile(DELIMETER);
Matcher m = p.matcher(arg);
while (m.find()) {
System.out.println(m.group(1));
}
}
}
What is the correct regex to get string between the delimeters?
In general, you cannot use a regex to match anything which can nest recursively. However, if you removed the ? from your regex, it would match from the first ( to the last ), which might be good enough, depending on what you expect the input to look like.

Get Substring from a String from __ [duplicate]

This question already has answers here:
substring between two delimiters
(6 answers)
Closed 5 years ago.
I want to extract subString from a String, starting from __(Double UnderScore) till a "(Double Quotes) or special character '[](),' is found.
I have been at it for some while now but cannot figure it out.
For Example: Input String : "NAME":"__NAME"
Required String : __NAME
Thanks for your time.
You can use this regex (__(.*?))[\"\[\]\(\),] to get what you want you can use :
String str = "\"NAME\":\"__NAME\"";
String regex = "(__(.*?))[\"\\[\\]\\(\\),]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Output
__NAME
regex demo
You could try following code
String input="\"NAME\":\"__NAME\"";
int startIndex=input.indexOf("__");
int lastIndex=input.length();
String output=input.substring(startIndex, (lastIndex-1));
System.out.println(output);
May this solution help you:
import java.util.*;
class test
{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String a=s.next();
int i=a.indexOf("__");
int j=a.indexOf('"',i);
System.out.println(a.substring(i,j));
}
}
In this firstly we calculate the index of __ and then we calculate the index of " after __.and then use substring method to get desired output.

Is there any efficient way to count the occurrence of a regex in String object? [duplicate]

This question already has answers here:
How can I count the number of matches for a regex?
(5 answers)
Closed 8 years ago.
is there any efficient standard java library except String's split method that can help in counting the occurance of a given regex pattern in a given String object
Guys please throw some comments on below approach:
String s = "AA---AA---AA";
String[] temp = s.split("AA");
int count = temp.length - 1;
The efficient way is to use a loop. The standard library doesn't provide a method to do this.
Something like this:
Matcher m = Pattern.compile(regex).matcher(input);
int count = 0;
while (m.find()) {
count++;
}
The approach of using String.split(separator) is probably1 less efficient, because it entails creating an array containing the string segments. There is certainly no sound reason to think that the computational complexity of split is different to the approach with the loop.
1 - I haven't bothered to measure this. If this is something that matters to you, you should construct a benchmark ...
import java.util.regex.*;
class RegexCount {
public static void main(String[] args) {
String test = "Test---Test---Test";
Pattern pattern = Pattern.compile("Test");
Matcher matcher = pattern.matcher(test);
int count = 0;
while (matcher.find())
count++;
System.out.println(count);
}
}
Output:
3

Categories

Resources