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.
Related
This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
I am new to Java.I am looking for a regular expression which will tell if the given string has "AND" placed at proper positions, that is, it is a valid AND operation.
Eg :
How AND why : VALID
Try AND succeed AND pass : VALID
Try succeed AND : INVALID ( since AND is at last index )
Try AND AND succeed AND pass : INVALID ( since there are 2 consecutive ANDs )
Here is a small working example to solve this problem,
public class MyClass {
public static void main(String args[]) {
String[] tests = {"How AND why", "Try AND succeed AND pass", "Try succeed AND", "Try AND AND succeed AND pass", "how ANDY why"};
for(String s: tests){
System.out.println(isValid(s));
}
}
public static boolean isValid(String str){
String[] splitString = str.split("\\bAND\\b", -1);
if(splitString.length == 1){
return false;
}
for(String s: splitString){
if (s.equals(" ") || s.equals("")){
return false;
}
}
return true;
}
}
I am splitting a string using the regex AND. If AND comes in the start or end of a string, there will always be an empty string in the output of str.split("AND", -1). Also, if an AND is followed by another, a space will also be there in str.split("AND", -1). So I check these two conditions in (s.equals(" ") || s.equals(""))
EDIT:
In order to handle strings like how ANDY why you can use word boundaries \b in the regex, which will match the whole word. So a regex like \\bAND\\b will not match the AND part in ANDY. Updated the code above to reflect this.
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.
This question already has answers here:
List of all special characters that need to be escaped in a regex
(10 answers)
Closed 4 years ago.
I wrote a Java program to find the pattern "Type": "Value" in a string.This is the pattern i wrote -> "Type[\W]*Value" . "Value" is replaced with actual value at run time
It works for strings like "Type":"Name" or "Type":"Name<" but when i pass parenthesis, it fails.
"Type":"Name(" - java.util.regex.PatternSyntaxException: Unclosed group near inex.
"Type":"Name()" - No match found.
I don't have much experience writing regular expression. Can someone please help me in understanding the issue.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
public class PatternFinder {
public static void main(String args[]) {
System.out.println(findPattern("Name","abcd7<","{\"response\":{\"Name\":\"abcd7<\"}}"));
System.out.println(findPattern("Name","abcd7(","{\"response\":{\"Name\":\"abcd7(\"}}"));
}
private static int findPattern(String InputType, String InputValue, String responseString) {
System.out.println("extractEncode" + responseString);
int indexOfInputPattern = -1;
String InputStringPattern = "InputType[\\W]*InputValue";
InputStringPattern = StringUtils.replaceEach(InputStringPattern, new String[] { "InputType", "InputValue" },
new String[] { InputType, InputValue });
System.out.println(InputStringPattern);
if (!StringUtils.isBlank(InputStringPattern)) {
Pattern pattern = Pattern.compile(InputStringPattern);
indexOfInputPattern = indexOf(pattern, responseString);
}
return indexOfInputPattern;
}
private static int indexOf(Pattern pattern, String s) {
System.out.println(pattern.toString()+" "+s);
Matcher matcher = pattern.matcher(s);
return matcher.find() ? matcher.end() : -1;
}
}
You can either escape the parentheses by adding a backslash in front of them or use Pattern.quote to escape parts you don't want to be interpreted as Pattern.
Read more here https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Pattern.html#quote(java.lang.String)
If you're searching for brackets () in regular expressions, you have to escape them with a backslash \. So you search for Name\(. This is because brackets have a special meaning in regular expressions.
To make things more complicated, \ is a special character in Java Strings, so you may find you have to escape that too. So your final expression is likely to look like Name\\(.
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.
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() + " ");
}
}
}