Extracting string from within round brackets in Java with regex - java

I'm trying to extract a string from round brackets.
Let's say, I have John Doe (123456789) and I want to output the string 123456789 only.
I have found this link and this regex:
/\(([^)]+)\)/g
However, I wasn't able to figure out how to get the wanted result.
Any help would be appreciated. Thanks!

String str="John Doe (123456789)";
System.out.println(str.substring(str.indexOf("(")+1,str.indexOf(")")));
Here I'm performing string operations. I'm not that much familiar with regex.

this works for me :
#Test
public void myTest() {
String test = "test (mytest)";
Pattern p = Pattern.compile("\\((.*?)\\)");
Matcher m = p.matcher(test);
while(m.find()) {
assertEquals("mytest", m.group(1));
}
}

You need to escape brackets in your regexp:
String in = "John Doe (123456789)";
Pattern p = Pattern.compile("\\((\\d*)\\)");
Matcher m = p.matcher(in);
while (m.find()) {
System.out.println(m.group(1));
}

In Java, you need to use
String pattern = "\\(([^()]+)\\)";
Then, the value you need is in .group(1).
String str = "John Doe (123456789)";
String rx = "\\(([^()]+)\\)";
Pattern ptrn = Pattern.compile(rx);
Matcher m = ptrn.matcher(str);
while (m.find()) {
System.out.println(m.group(1));
}
See IDEONE demo

Related

Using regex in java to get a word from a string [duplicate]

This question already has answers here:
Difference between matches() and find() in Java Regex
(5 answers)
Closed 3 years ago.
I need to find the word "best" in a string using regex but it's throwing a "no match found" error. What am I doing wrong?
Pattern pattern = Pattern.compile("(best)");
String theString = "the best of";
Matcher matcher = pattern.matcher(theString);
matcher.matches();
String whatYouNeed = matcher.group(1);
Log.d(String.valueOf(LOG), whatYouNeed);
As per your requirement you have to find the string "best" in "the best of", so find() method suits your requirement instead of matches(). Please find the sample code snippet below:
Pattern pattern = Pattern.compile("best");
String theString = "the best of";
Matcher matcher = pattern.matcher(theString);
if(matcher.find()) {
System.out.println("found");
}else {
System.out.println("not found");
}
}
Use find() not matches!
public static void main(String[] args){
Pattern pattern = Pattern.compile("(best)");
String theString = "the best of";
Matcher matcher = pattern.matcher(theString);
if(matcher.find())
System.out.println("Hi!");
}
What I think you want is this.
String theString = "the best of";
String regex = "(best)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(theString);
while (m.find()) {
String result = m.group(1);
System.out.println("found: " + result);
}
outputs:
found: best

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

Regex - find data inside left and right encloses

I have this string:
text=123+456+789&xxxxxxxxx&yyyyyyyyyy&zzzzzzzzzzz
I need to extract 123+456+789
What I done so far is:
String s = "text=123+456+789&xxxxxxxxx&yyyyyyyyyy&zzzzzzzzzzz";
String ps = "text=(.*)&";
Pattern p = Pattern.compile(ps);
Matcher m = p.matcher(s);
if (m.find()){
System.out.println(m.group(0));
System.out.println(m.group(1));
}
And I got all text until the last & which is: 123+456+789&xxxxxxxxx&yyyyyyyyyy while the requested output is: 123+456+789
Any suggestions how to fix it (regex is mandatory)?
Use a negated character class:
String ps = "text=([^&]*)";
The value you need will be in Group 1.
The [^&] matches any character but an ampersand.
You almost getting, you need to make your regex lazy (or non greedy) like this:
String ps = "text=(.*?)&";
here ---^
Working demo
Try this regex :
([0-9+]+)
Link : https://regex101.com/r/xU2zF4/1
java code :
String s = "text=123+456+789&xxxxxxxxx&yyyyyyyyyy&zzzzzzzzzzz";
String ps = "([0-9+]+)";
Pattern p = Pattern.compile(ps);
Matcher m = p.matcher(s);
if (m.find()){
System.out.println(m.group(0)); // value of s
System.out.println(m.group(1)); // returns 123+456+789
}

Java regex - why did the Matcher find extra characters?

I was experimenting trying to extract the 't' and 'f' flags from here.
So I was surprised to see extra characters in the output. Apparently the matcher backtracked - I dont understand why. What should be the correct regex?
System.out.println("searching...");
// "Sun:\\s Mon:\\s Tue:\\s Wed:\\s Thu:\\s Fri:\\s Sat:\\s "
Pattern p = Pattern.compile("[t|f]");
Matcher m = p.matcher("Sun:t Mon:f Tue:t Wed:t Thu:f Fri:t Sat:f ");
while (m.find()) {
System.out.println(m.group());
}
Output:
searching...
t
f
t
t
f
t
t
f
Sat has a t in it. Try ":([tf])" instead.
Pattern p = Pattern.compile(":([tf])");
Matcher m = p.matcher("Sun:t Mon:f Tue:t Wed:t Thu:f Fri:t Sat:f ");
while (m.find()) {
System.out.println(m.group(1));
}

Extract substring from string - regex

I have a String say:
<encoded:2,Message request>
Now I want to extract 2 and Message request from the line above.
private final String pString = "<encoded:[0-9]+,.*>";
private final Pattern pattern = Pattern.compile(pString);
private void parseAndDisplay(String line) {
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
while(matcher.find()) {
String s = matcher.group();
System.out.println("=====>"+s);
}
}
}
This doesn't retrieve it. What is wrong with it
You have to define groups in your regex:
"<encoded:([0-9]+),(.*?)>"
or
"<encoded:(\\d+),([^>]*)"
try
String s = "<encoded:2,Message request>";
String s1 = s.replaceAll("<encoded:(\\d+?),.*", "$1");
String s2 = s.replaceAll("<encoded:\\d+?,(.*)>", "$1");
Try
"<encoded:([0-9]+),([^>]*)"
Also, as suggested in other comments, use group(1) and group(2)
Try this out :
Matcher matcher = Pattern.compile("<encoded:(\\d+)\\,([\\w\\s]+)",Pattern.CASE_INSENSITIVE).matcher("<encoded:2,Message request>");
while (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}

Categories