I'm trying to parse from a string like below
"name1(value1),name2(value2),name3(value3),name4(value4),........" and so it goes
How can I do it recursively with groups?
String s = "name1(value1),name2(value2),name3(value3),name4(value4),";
Pattern p = Pattern.compile(".*?\\((.*?)\\)");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(m.group(1));
}
i would rather use the java String operations to get to the values but if you want to use regex, you could use something that looks like that:
[^\(]*\([^\)]*\),
Should be quite stable
You can test it here:
http://regexr.com?2u7u3
You can use matcher.find, try something like this:
String input = "name1(value1),name2(value2),name3(value3),name4(value4)";
Matcher matcher = Pattern.compile(".*?[(].*?[)]").matcher(input);
while(matcher.find()) {
System.out.println(matcher.group(0));
}
or just use String.split like this:
String input = "name1(value1),name2(value2),name3(value3),name4(value4)";
String[] split = input.split(",");
Related
I want to extract numbers and strings from a string.
Ex.
"TU111 1998 SUMMER”
"TU-232 SU 1999"
"TU232 1999 SUMMER"
I was able to get it using two patterns Pattern.compile("\\d+") and Pattern.compile("[a-zA-Z]+")
Is there a way to get it using one pattern?
The expected outcome should be
1=>TU 2=> 111/232 3=>1998/1999 4=>SUMMER/SU
You can just pipe the two regexes together:
[0-9]+|[a-zA-Z]+
Demo
Try with this.
Pattern pattern = Pattern.compile("((\\d+)|([a-zA-Z]+))");
Matcher matcher = pattern.matcher("TU111 1998 SUMMER");
while (matcher.find()) {
System.out.println(matcher.group());
}
Hey you have to use 2 regexes [a-zA-Z]+|[0-9]+ and maybe the different code I wrote below might give you a hint.just updating Pattern.compile() and string will be enough.
Pattern p = Pattern.compile("-?\\d+(,\\d+)*?\\.?\\d+?");
List<String> numbers = new ArrayList<String>();
Matcher m = p.matcher("your string");
while (m.find()) {
numbers.add(m.group());
}
System.out.println(numbers);
I have a string like this:
String unparsed = "[thing.1][thin2g]"
I want to turn it into
"thing.1"
"thin2g"
Been trying for a while with regex expressions but nothing. Any thoughts? Thanks!
EDIT:
Tried:
String unparsed = "[thing.1][thin2g]"
String substring = unparsed.substring(1,unparsed.length - 1)
substring.replace("][","`")
String[] split = substring.split('`')
for(int i=0;i<split.length;i++)
{
System.out.println(split[i])
}
But this seems kinda heavy, was looking for something more elegant
String unparsed = "[thing.1][thin2g]";
Pattern pattern = Pattern.compile("\\[(.*?)\\]");
Matcher matcher = pattern.matcher(unparsed);
while(matcher.find()){
System.out.println(matcher.group(1));
}
My regex is not good. But it does parse the string into what you want.
\[\s*\w.*?\]
I never use regular expressions before but this one should work
I am using Java. I need to parse the following line using regex :
<actions>::=<action><action>|X|<game>|alpha
It should give me tokens <action>, <action>,X and <game>
What kind of regex will work?
I was trying sth like: "<[a-zA-Z]>" but that doesn't take care of X or alpha.
You can try something like this:
String str="<actions>::=<action><action>|X|<game>|alpha";
str=str.split("=")[1];
Pattern pattern = Pattern.compile("<.*?>|\\|.*?\\|");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
You should have something like this:
String input = "<actions>::=<action><action>|X|<game>|alpha";
Matcher matcher = Pattern.compile("(<[^>]+>)(<[^>]+>)\\|([^|]+)\\|(<[^|]+>)").matcher(input);
while (matcher.find()) {
System.out.println(matcher.group().replaceAll("\\|", ""));
}
You didn't specefied if you want to return alpha or not, in this case, it doesn't return it.
You can return alpha by adding |\\w* to the end of the regex I wrote.
This will return:
<action><action>X<game>
From the original pattern it is not clear if you mean that literally there are <> in the pattern or not, i'll go with that assumption.
String pattern="<actions>::=<(.*?)><(.+?)>\|(.+)\|<(.*?)\|alpha";
For the java code you can use Pattern and Matcher: here is the basic idea:
Pattern p = Pattern.compile(pattern, Pattern.DOTALL|Pattern.MULTILINE);
Matcher m = p.matcher(text);
m.find();
for (int g = 1; g <= m.groupCount(); g++) {
// use your four groups here..
}
You can use following Java regex:
Pattern pattern = Pattern.compile
("::=(<[^>]+>)(<[^>]+>)\\|([^|]+)\\|(<[^>]+>)\\|(\\w+)$");
String output = "";
pattern = Pattern.compile(">Part\s.");
matcher = pattern.matcher(docToProcess);
while (matcher.find()) {
match = matcher.group();
}
I'm trying to use the above code to find the pattern >Part\s. inside docToProcess (Which is a string of a large xml document) and then what I want to do is replace the content that matches the pattern with <ref></ref>
Any ideas how I can make the output variable equal to docToProcess except with the replacements as indicated above?
EDIT: I need to use the matcher somehow when replacing. I can't just use replaceAll()
You can use String#replaceAll method. It takes a Regex as first parameter: -
String output = docToProcess.replaceAll(">Part\\s\\.", "<ref></ref>");
Note that, dot (.) is a special meta-character in regex, which matches everything, and not just a dot(.). So, you need to escape it, unless you really wanted to match any character after >Part\\s. And you need to add 2 backslashes to escape in Java.
If you want to use Matcher class, the you can use Matcher.appendReplacement method: -
String docToProcess = "XYZ>Part .asdf";
Pattern p = Pattern.compile(">Part\\s\\.");
Matcher m = p.matcher(docToProcess);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "<ref></ref>");
}
m.appendTail(sb);
System.out.println(sb.toString());
OUTPUT : -
"XYZ<ref></ref>asdf"
This is what you need:
String docToProcess = "... your xml here ...";
Pattern pattern = Pattern.compile(">Part\\s.");
Matcher matcher = pattern.matcher(docToProcess);
StringBuffer output = new StringBuffer();
while (matcher.find()) matcher.appendReplacement(output, "<ref></ref>");
matcher.appendTail(output);
Unfortunately, you can't use the StringBuilder due to historical constraints on the Java API.
docToProcess.replaceAll(">Part\\s[.]", "<ref></ref>");
String output = docToProcess.replaceAll(">Part\\s\\.", "<ref></ref>");
I have a file with some custom tags and I'd like to write a regular expression to extract the string between the tags. For example if my tag is:
[customtag]String I want to extract[/customtag]
How would I write a regular expression to extract only the string between the tags. This code seems like a step in the right direction:
Pattern p = Pattern.compile("[customtag](.+?)[/customtag]");
Matcher m = p.matcher("[customtag]String I want to extract[/customtag]");
Not sure what to do next. Any ideas? Thanks.
You're on the right track. Now you just need to extract the desired group, as follows:
final Pattern pattern = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);
final Matcher matcher = pattern.matcher("<tag>String I want to extract</tag>");
matcher.find();
System.out.println(matcher.group(1)); // Prints String I want to extract
If you want to extract multiple hits, try this:
public static void main(String[] args) {
final String str = "<tag>apple</tag><b>hello</b><tag>orange</tag><tag>pear</tag>";
System.out.println(Arrays.toString(getTagValues(str).toArray())); // Prints [apple, orange, pear]
}
private static final Pattern TAG_REGEX = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);
private static List<String> getTagValues(final String str) {
final List<String> tagValues = new ArrayList<String>();
final Matcher matcher = TAG_REGEX.matcher(str);
while (matcher.find()) {
tagValues.add(matcher.group(1));
}
return tagValues;
}
However, I agree that regular expressions are not the best answer here. I'd use XPath to find elements I'm interested in. See The Java XPath API for more info.
To be quite honest, regular expressions are not the best idea for this type of parsing. The regular expression you posted will probably work great for simple cases, but if things get more complex you are going to have huge problems (same reason why you cant reliably parse HTML with regular expressions). I know you probably don't want to hear this, I know I didn't when I asked the same type of questions, but string parsing became WAY more reliable for me after I stopped trying to use regular expressions for everything.
jTopas is an AWESOME tokenizer that makes it quite easy to write parsers by hand (I STRONGLY suggest jtopas over the standard java scanner/etc.. libraries). If you want to see jtopas in action, here are some parsers I wrote using jTopas to parse this type of file
If you are parsing XML files, you should be using an xml parser library. Dont do it youself unless you are just doing it for fun, there are plently of proven options out there
A generic,simpler and a bit primitive approach to find tag, attribute and value
Pattern pattern = Pattern.compile("<(\\w+)( +.+)*>((.*))</\\1>");
System.out.println(pattern.matcher("<asd> TEST</asd>").find());
System.out.println(pattern.matcher("<asd TEST</asd>").find());
System.out.println(pattern.matcher("<asd attr='3'> TEST</asd>").find());
System.out.println(pattern.matcher("<asd> <x>TEST<x>asd>").find());
System.out.println("-------");
Matcher matcher = pattern.matcher("<as x> TEST</as>");
if (matcher.find()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println(i + ":" + matcher.group(i));
}
}
String s = "<B><G>Test</G></B><C>Test1</C>";
String pattern ="\\<(.+)\\>([^\\<\\>]+)\\<\\/\\1\\>";
int count = 0;
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(s);
while(m.find())
{
System.out.println(m.group(2));
count++;
}
Try this:
Pattern p = Pattern.compile(?<=\\<(any_tag)\\>)(\\s*.*\\s*)(?=\\<\\/(any_tag)\\>);
Matcher m = p.matcher(anyString);
For example:
String str = "<TR> <TD>1Q Ene</TD> <TD>3.08%</TD> </TR>";
Pattern p = Pattern.compile("(?<=\\<TD\\>)(\\s*.*\\s*)(?=\\<\\/TD\\>)");
Matcher m = p.matcher(str);
while(m.find()){
Log.e("Regex"," Regex result: " + m.group())
}
Output:
10 Ene
3.08%
final Pattern pattern = Pattern.compile("tag\\](.+?)\\[/tag");
final Matcher matcher = pattern.matcher("[tag]String I want to extract[/tag]");
matcher.find();
System.out.println(matcher.group(1));
I prefix this reply with "you shouldn't use a regular expression to parse XML -- it's only going to result in edge cases that don't work right, and a forever-increasing-in-complexity regex while you try to fix it."
That being said, you need to proceed by matching the string and grabbing the group you want:
if (m.matches())
{
String result = m.group(1);
// do something with result
}
This works for me, use in your main method below Scanner input. Works for Hackerrank "Tag Content Extractor" also.
boolean matchFound = false;
Pattern r = Pattern.compile("<(.+)>([^<]+)</\\1>");
Matcher m = r.matcher(line);
while (m.find()) {
System.out.println(m.group(2));
matchFound = true;
}
if ( ! matchFound) {
System.out.println("None");
}
testCases--;