Java Regular Expressions - java

I am trying to write something like this:
Pattern p = Pattern.compile("Mar\\w");
Matcher m = p.matcher("Mary");
String result = m.replaceAll("\\w");
The result would ideally be "y". Any ideas?

Your question is not so clear, but I think you want to use a lookahead:
Pattern p = Pattern.compile("Mar(?=\\w)");
Matcher m = p.matcher("Mary");
String result = m.replaceAll("");
See it online: ideone
Or you could use a capturing group:
Pattern p = Pattern.compile("Mar(\\w)");
Matcher m = p.matcher("Mary");
String result = m.replaceAll("$1");
See it online: ideone

Related

Java regex matcher always returns false

I have a string expression from which I need to get some values. The string is as follows
#min({(((fields['example6'].value + fields['example5'].value) * ((fields['example1'].value*5)+fields['example2'].value+fields['example3'].value-fields['example4'].value)) * 0.15),15,9.087})
From this stribg, I need to obtain a string array list which contains the values such as "example1", "example2" and so on.
I have a Java method which looks like this:
String regex = "/fields\\[['\"]([\\w\\s]+)['\"]\\]/g";
ArrayList<String> arL = new ArrayList<String>();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(expression);
while(m.find()){
arL.add(m.group());
}
But m.find() always returns false. Is there anything I'm missing?
The problem is with the '/'s. If what you want to extract is only the field name, you should use m.group(1):
String regex = "fields\\[['\"]([\\w\\s]+)['\"]\\]";
ArrayList<String> arL = new ArrayList<String>();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(expression);
while(m.find()){
arL.add(m.group(1));
}
The main issue you seem to have is that you are using delimiters (as in PHP or Perl or JavaScript) that cannot be used in a Java regex. Also, you have your matches in the first capturing group, but you are using group() that returns the whole match (including fields[').
Here is a working code:
String str = "#min({(((fields['example6'].value + fields['example5'].value) * ((fields['example1'].value*5)+fields['example2'].value+fields['example3'].value-fields['example4'].value)) * 0.15),15,9.087})";
ArrayList<String> arL = new ArrayList<String>();
String rx = "(?<=fields\\[['\"])[\\w\\s]*(?=['\"]\\])";
Pattern ptrn = Pattern.compile(rx);
Matcher m = ptrn.matcher(str);
while (m.find()) {
arL.add(m.group());
}
Here is a working IDEONE demo
Note that I have added look-arounds to extract just the texts between 's with group().

Storing backreferences from regex expression for later use

If I have,
String str = "11";
Pattern p = Pattern.compile("(\\d)\\1");
Matcher m = p.matcher(str);
How do I store use the result of \1 later? For example I want to do,
String str = "123123";
Pattern p = Pattern.compile("(\\d)\\1");
Matcher m = p.matcher(str);
String dependantString = //make this whatever was in group 1 of the pattern.
Is that possible?
You need to first call Matcher#find and then Matcher#group(1) like this:
String str = "123123";
Pattern p = Pattern.compile("(\\d+)\\1");
Matcher m = p.matcher(str);
if (m.find())
System.out.println( m.group(1) ); // 123
PS: Your regex also needed some correction to use \\d+ instead of \\d.

Regex parse string in java

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+)$");

Matching a string to a regex from html input

I'm having a little trouble figuring out what to do.
Basically using java I'm trying to:
Reading in the html from a website
I want to find the content after a certain string in this case being
title="
Store that in a string.
The first and last steps are simple for me but I'm having no luck (and never had with regex).
I believe this is the beginning of what I need:
String regex = "(?<=title=\")\\S+";
Pattern name = Pattern.compile(regex);
After that I have no clue. Any help?
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String EXAMPLE_TEST = "......";
Pattern pattern = Pattern.compile("(?<=title=\")(\\S+)")
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
while (matcher.find()) {
System.out.println(matcher.group());
}
Note: You might consider to use regex pattern (?<=title=\")([^\"]*)
List<String> result_list = new ArrayList<String>();
Pattern p = Pattern.compile("title=\"(.*)\"");
Matcher m = p.matcher("title=\"test\"");
boolean result = m.find();
while(result)
{
result_list.add(m.group(0));
result = m.find();
}

Java regex to extract text between tags

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--;

Categories