This question already has answers here:
How to match string within parentheses (nested) in Java?
(2 answers)
Closed 6 years ago.
Is there a regex to extract sub strings from a string containing multiple parantheses?
For example my string is
String str = "(A(B(C(D(x)))))";
I want to print all the sub strings that lie within any pair of parantheses :
A(B(C(D(x))))
B(C(D(x)))
C(D(x))
D(x)
x
I tried using regex :
Matcher m = Pattern.compile("\\((.*?)\\)").matcher(str);
while (m.find()) {
System.out.println(m.group(1));
}
But this only extracts the sub string it finds between 1st pair of parentheses.
I have developed what you requested but not just with regex, but a recursive function. Please check following code:
public static void main(String[] args)
{
String str = "(A(B(C(D(x)))))";
findStuff(str);
}
public static void findStuff(String str){
String pattern = "\\((.+)\\)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(str);
while (m.find())
{
String sub = m.group(1);
System.out.println(" Word: " + sub);
findStuff(sub);
}
}
Related
This question already has answers here:
Regex whitespace word boundary
(3 answers)
Closed 3 years ago.
public static void main(String args[]) {
findExactWord find = new findExactWord();
String fullString = "reports of a chemical (reaction; in the kitchen) area found a male employee suffering from nausea";
System.out.println(find.isContainExactWord(fullString, "chemical (reaction; in the kitchen)"));
}
private boolean isContainExactWord(String fullString, String partWord){
String pattern = "\\b"+partWord+"\\b";
System.out.println("Pattern : "+partWord);
Pattern p=Pattern.compile(pattern);
Matcher m=p.matcher(fullString);
return m.find();
}
I want this result to be - true.
Search input is : "chemical (reaction; in the kitchen)
this should search all characters exactly as is.
output is now : false
String pattern = partWord;
System.out.println("Pattern : " + partWord);
Pattern p = Pattern.compile(pattern, Pattern.LITERAL);
Matcher m = p.matcher(fullString);
return m.find();
now the tested version ;-)
it matches special characters and ignores newlines
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.
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
This question already has answers here:
Using Java to find substring of a bigger string using Regular Expression
(11 answers)
Closed 7 years ago.
I'm trying to extract a piece of string from a larger string.
Example:
String value;
...etc...
value = someMethod();
// Here value equals a large string text
value;
I want to extract a subset of this string which begins with "path=" and everything after it.
Elaborated Example:
if value equals:
StartTopic topic=testParser, multiCopy=false, required=true,
all=false, path=/Return/ReturnData/IRSW2
I want only "path=/Return/ReturnData/IRSW2" so on and so forth.
How could I do this in Java?
This is what I currently have:
if(value.contains("path")) {
String regexStr = FileUtils.readFileToString(new File("regex.txt"));
String escapedRegex = StringEscapeUtils.escapeJava(regexStr);
System.out.println(value.replaceAll(escapedRegex), "$1");
}
This doesn't work! Just outputs the whole string again
Contents of regex.txt:
/path=([^\,]+)/
This should do the trick
String s = "if value=StartTopic topic=testParser, multiCopy=false, required=true, all=false, path=/Return/ReturnData/IRSW2";
String regex= "path=[^\\,]*";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
if(m.find()) {
System.out.println(m.group());
}
You can also use:
String regex = "(?<=path=)[^\\,]*";
insted, so you will get only /Return/ReturnData/IRSW2 part.
Use the function indexOf() to find the index of 'path='
String str = "path=/Return/ReturnData/IRSW2";
System.out.println(str.substring(str.indexOf("path=") + 5));
This question already has answers here:
Collapse and Capture a Repeating Pattern in a Single Regex Expression
(5 answers)
Closed 9 years ago.
I wanna parse a string like {"aaa","bbb", "ccc"} to aaa,bbb,ccc. How can I do it in regex in java? I've tried to write code as below:
String s = "{\"aaa\",\"bbb\", \"ccc\"}";
Pattern pattern = Pattern.compile("\\{\\\"([\\w]*)\\\"([\\s]*,[\\s]*\\\"([\\w]*)\\\")*}");
Matcher matcher = pattern.matcher(s);
if(matcher.find()) {
StringBuilder sb = new StringBuilder();
int cnt = matcher.groupCount();
for(int i = 0; i < cnt; ++i) {
System.out.println(matcher.group(i));
}
}
but the output is
{"aaa","bbb", "ccc"}
aaa
, "ccc"
I have a feeling that this is something about group and no-greedy match, but I don't know how to write it, could anyone help me? Thanks a lot!
P.S. I know how to do it with method like String.replace, I just wanna know could it be done by regex. Thanks
Thanks for all your answers and time, but what I want at first is a delegate solution using regex in java, especially group in regex. I want to know how to use group to solve it.
RegEx ONLY matching: quite complex
RegEx Pattern: (?:\{(?=(?:"[^"]+"(?:, ?|(?=\})))*\})|(?!^)\G, ?)"([^"]+)"
Note: it needs the global modifier g, needs escaping, works with unlimited number of tokens
Explained demo here: http://regex101.com/r/iE9gS1
Try this.
import java.util.*;
public class Main{
public static void main(String[] args){
String s = "{\"aaa\",\"bbb\", \"ccc\"}";
s = s.substring(1,s.length() -1 );
s = s.replace("\"","");
String[] sa = s.split(", ?");
for (int i = 0; i < sa.length; i++)
System.out.println(sa[i]);
}
}
Try this sample code :
public class RegexTester {
public static void main(String[] args) throws Exception {
String data = "{\"aaa\",\"bbb\", \"ccc\"}";
String modifiedData = data.replaceAll("\\{|\"|\\}", "");
System.out.println("Modified data : " + modifiedData);
}
Using regex try this pattarn :
Pattern pattern = Pattern.compile("\\{\"(.+?)\"(,?)\"(.+?)\"(,?)\\s*\"(.+?)\"");
Matcher matcher = pattern.matcher(data);
System.out.println("Started");
while (matcher.find()) {
System.out.print(matcher.group(1));
System.out.print(matcher.group(2));
System.out.print(matcher.group(3));
System.out.print(matcher.group(4));
System.out.print(matcher.group(5));
}
Hope this addresses your issue.