regex - Java Regular expression matching square bracket [duplicate] - java

This question already has answers here:
Regular expression to extract text between square brackets
(15 answers)
Closed 12 months ago.
Would someone kindly demonstrate what the regular expession would be for matching the square brackets?
I'm currently using java.util.regex.
For example, let's say we have the following line:
public static void main (String[] args) {
I need to match only the OPEN square bracket [ and next, the close square bracket ].
I'm not saying I need to match the text between the square brackets.
I have tried with
[\\]]
and
\\]
Unfortunately, it matches the text as well and I need to match only [ or ].
The weird thing is, when I try to match the { with [\\}], it works!
Thoughts?

You can do it using:
String text = "[This is the text]";
String patternString = "\\[.*.\\]";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
System.out.println("Matcher? " + matcher.matches());
This return true if the text has a [ and ] and false if it doesn't
Hope this can help you.
Thanks.

Related

Parse data between the brackets from a string - Java [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 3 years ago.
I am trying to parse data from the [] in a String in java
String text = "some text [Karan] some text";
I want to the computer to read Karan present inside the brackets
I have tried String.split() method but it packs it into an array which I don't want.
Is there any way to do this. Thank you
You can use regex like this:
String text = "some text [Karan] some [test2] text [test3] [test4] 22[test5]";
Pattern pattern = Pattern.compile("(?<=\\[).*?(?=\\])");
//or use this regex,it works well too
//Pattern pattern = Pattern.compile("(?<=\\[)[^\\[\\]]*(?=\\])");
Matcher matcher = pattern.matcher(text);
while(matcher.find()){
System.out.println(matcher.group());
}
and the result is Karan,test2,test3,test4,test5.
Regex is useful for processing text.This improved version of regular is using "Positive and Negative Lookbehind".Thanks for Matthieu's suggestions.
You might want to use the String.substring method in combination with String.indexOf.
Here is a short description of how you would extract text between brackets [] using these two methods:
Get the index of the first bracket [ character using String.indexOf method. (let's call this value start)
Get the index of the second bracket ] character using String.indexOf method (let's call this value end)
Call .substring on the string you are extracting information from with
text.substring(start+1, end)
Note how the first index start+1 is inclusive and end is exclusive.
Looks like this then:
String text = "some text [Karen] some text";
text = text.substring(text.indexOf("[") + 1, text.indexOf("]"));
System.out.println(text);

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.

Java Regular expression matching square brackets [duplicate]

This question already has answers here:
Regular expression to extract text between square brackets
(15 answers)
Closed 12 months ago.
I'm trying to do the following using regular expression (java replaceAll):
**Input:**
Test[Test1][Test2]Test3
**Output**
TestTest3
In short, i need to remove everything inside square brackets including square brackets.
I'm trying this, but it doesn't work:
\\[(.*?)\\]
Would you be able to help?
Thanks,Sash
You can try this regex:
\[[^\[]*\]
and replace by empty
Demo
Sample Java Source:
final String regex = "\\[[^\\[]*\\]";
final String string = "Test[Test1][Test2]Test3\n";
final String subst = "";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
final String result = matcher.replaceAll(subst);
System.out.println(result);
Your original pattern works for me:
String input = "Test[Test1][Test2]Test3";
input = input.replaceAll("\\[.*?\\]", "");
System.out.println(input);
Output:
TestTest3
Note that you don't need the parentheses inside the brackets. You would use that if you planned to capture the contents in between each pair of brackets, which in your case you don't need. It isn't wrong to have them in there, just not necessary.
Demo here:
Rextester
\[\w+]
This works for me, this regex matches all the words which are enclosed in square brackets.

How to extract a string regular expression using java? [duplicate]

This question already has answers here:
How do you access the matched groups in a JavaScript regular expression?
(23 answers)
Closed 6 years ago.
I wanted to extract what ever is within the below tokens
${FNAME} ${LNAME} ${123}
FNAME LNAME 123.
I tried the below.
public static void main(String[] args) {
String input = "{FNAME} ${LNAME} ${123}";
Pattern p = Pattern.compile("\\$\\{");
Matcher m = p.matcher(input);
while (m.find()) {
System.out.println("Found a " + m.group() + ".");
}
}
Ended up wrongly. Beginner to reg expressions.
You should use lazy quantifier ? and capture group () like this.
Regex: \$\{(.*?)\}
Replacement to do: \1 for first captured group.
Regex101 Demo

regular expression to extract string from java code [duplicate]

This question already has answers here:
Regex to replace all string literals in a Java file
(4 answers)
Closed 8 years ago.
The sample source code to match is
String string="welcome";
String k="a\"welcome";
I am using "(\"[^(\")]*\")" regex in java.
But this extracts
0:"welcome"
0:"a\"
Expected output is
0:"welcome"
0:"a\"welcome"
What change should i make in regex to get the expected output ?
Java source :
private static String pattern1="(\"[^(\")]*\")";
public void getStrings(){
Pattern r = Pattern.compile(pattern1);
Matcher m = r.matcher("String string=\"welcome\";\n" +
"String k=\"a\\\"welcome\";");
while(m.find()){
System.out.println("0:"+m.group(0));
}
}
Just use lookahead and lookbehind in your regex,,
(?<==)(".*?")(?=;)
Get the value from group index 1.
DEMO
Pattern r = Pattern.compile("(?<==)(\".*?\")(?=;)");
Matcher m = r.matcher("String string=\"welcome\";\n" +
"String k=\"a\\\"welcome\";");
while(m.find()){
System.out.println("0:"+m.group(1));
}
Output:
0:"welcome"
0:"a\"welcome"
OR
Use the greediness of *,
Pattern r = Pattern.compile("(\".*\")");
OR
It skips the double quotes which are preceded by a backslash,
Pattern r = Pattern.compile("(\\\".*?(?<=[^\\\\])\\\")");
Why do you even bother with variable assignment. You know that everything within "" is a string.
"(.+)"\s*; should do it just fine.

Categories

Resources