This code works in javascript, is it possible to do something similar in java? (get the value of a wildcard in a string)
var a = "HI MY NAME IS BOB"
var b = /HI MY NAME IS (.*)/
alert("HI " + b.exec(a)[1])
Probably you need to find captured group #1:
Pattern p = Pattern.compile("(?i)Hi MY NAME IS (.*)");
Matcher m = p.matcher("Hi MY NAME IS BOB");
if (m.find()) {
System.out.println( "Group #1: " + m.group(1) ); // BOB
}
(?i) is for ignore case match
m.group(1) will give value of first captured group from your regex i.e. (.*)
What you're looking for is the java.util.regex package.
The syntax of regular expressions is a whole different answer, but I'll assume you're somewhat familiar with it here.
To use a regex in Java, you'll need to create two objects, a Pattern and a Matcher.
Quoting the documentation, a Pattern object is "A compiled representation of a regular expression", and a Matcher object is "An engine that performs match operations on a character sequence by interpreting a Pattern."
In other words, you use a Pattern to define your regex, and a Matcher to apply it.
So let's take this line-by-line:
import java.util.regex.*;
String a = "MY NAME is BOB";
Obviously, you need to import the package and define the string you're going to apply the regex to.
Pattern wildcard = Pattern.compile("HI MY NAME IS (.*)");
Pattern.compile takes a String representing a regex and returns a Pattern.
Matcher match = wildcard.matcher(a);
Pattern objects have an instance method, matcher, that takes the string you want to apply the Pattern to, and returns a Matcher.
System.out.println(match.group(1));
Calling match.group(n) returns the string matching the nth group of parentheses (to be more precise, the nth capturing group) in your regex. match.group(0), which is equivalent to match.group(), returns the string representing your entire match. In this case, we're using match.group(1) because we want to match the only set of parentheses in our regex - the (.*) at the end.
Putting it all together, we get:
import java.util.regex.*;
String a = "MY NAME is BOB";
Pattern wildcard = Pattern.compile("HI MY NAME IS (.*)");
Matcher match = wildcard.matcher(a);
System.out.println(match.group(1));
The class you need is Pattern. It is similar to regex in its functions, but the mechanics are different. Here is a link to the documentation.
This is not entirely what you asked for but I want to try to be little helpful. You can print out "BOB" using the substring(). Here is what worked for me: String a = new String("Hi my name is Bob");
System.out.printf("This print as Bob\n%s",a.substring(14)); The substring starts at index 14 and prints to the end of the string.
Related
I am trying to match a series of string thats looks like this:
item1 = "some value"
item2 = "some value"
I have some strings, though, that look like this:
item-one = "some new value"
item-two = "some new value"
I am trying to parse it using regular expressions, but I can't get it to match the optional hyphen.
Here is my regex string:
Pattern p = Pattern.compile("^(\\w+[-]?)\\w+?\\s+=\\s+\"(.*)\"");
Matcher m = p.matcher(line);
m.find();
String option = m.group(1);
String value = m.group(2);
May someone please tell me what I could be doing wrong.
Thank you
I suspect that main reason of your problem is that you are expecting w+? to make w+ optional, where in reality it will make + quantifier reluctant so regex will still try to find at least one or more \\w here, consuming last character from ^(\\w+.
Maybe try this way
Pattern.compile("^(\\w+(?:-\\w+)?)\\s+=\\s+\"(.*?)\"");
in (\\w+(?:-\\w+)?) -> (?:-\\w+) part will create non-capturing group (regex wont count it as group so (.*?) will be group(2) even if this part will exist) and ? after it will make this part optional.
in \"(.*?)\" *? is reluctant quantifier which will make regex to look for minimal match that exist between quotation marks.
Demo
Your problem is that you have the ? in the wrong place:
Try this regex:
^((\\w+-)?\\w+)\\s*=\\s*\"([^\"]+)\"
But use groups 1 and 3.
I've cleaned up the regex a bit too
This regex should work for you:
^\w[\w-]*(?<=\w)\s*=\s*\"([^"]*)\"
In Java:
Pattern p = Pattern.compile("^\\w[\\w-]*(?<=\\w)\\s*=\\s*\"([^\"]*)\"");
Live Demo: http://www.rubular.com/r/0CvByDnj5H
You want something like this:
([\w\-]+)\s*=\s*"([^"]*)"
With extra backslashes for Java:
([\\w\\-]+)\\s*=\\s*\"([^\"]*)\"
If you expect other symbols to start appearing in the variable name, you could make it a character class like [^=\s] to accept any characters not = or whitespace, for example.
For a given input string and a given pattern K, I want to extract every occurrence of K (or some part of it (using groups)) from the string and check that the entire string matches K* (as in it consists of 0 or more K's with no other characters).
But I would like to do this in a single pass using regular expressions. More specifically, I'm currently finding the pattern using Matcher.find, but this is not strictly required.
How would I do this?
I already found a solution (and posted an answer), but would like to know if there is specific regex or Matcher functionality that addresses / can address this issue, or simply if there are better / different ways of doing it. But, even if not, I still think it's an interesting question.
Example:
Pattern: <[0-9]> (a single digit in <>)
Valid input: <1><2><3>
Invalid inputs:
<1><2>a<3>
<1><2>3
Oh look, a flying monkey!
<1><2><3
Code to do it in 2 passes with matches:
boolean products(String products)
{
String regex = "(<[0-9]>)";
Pattern pAll = Pattern.compile(regex + "*");
if (!pAll.matcher(products).matches())
return false;
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(products);
while (matcher.find())
System.out.println(matcher.group());
return true;
}
1. Defining the problem
Since it is not clear what to output when the whole string does not match pattern K*, I will redefine the problem to make it clear what to output in such case.
Given any pattern K:
Check that the string has the pattern K*.
If the string has pattern K*, then split the string into non-overlapping tokens that matches K.
If the string only has prefix that matches pattern K*, then pick the prefix that is chosen by K*+1, and split the prefix into tokens that matches K.
1 I don't know if there is anyway to get the longest prefix that matches K. Of course, you can always remove the last character one by one and test against K* until it matches, but it is obviously inefficient.
Unless specify otherwise, whatever I write below will follow my problem description above. Note that the 3rd bullet point of the problem is to resolve the ambiguity on which prefix string to take.
2. Repeated capturing group in .NET
The problem above can be solved if we have the solution to the problem:
Given a pattern (K)*, which is a repeated capturing group, get the captured text for all the repetitions, instead of only the last repetition.
In the case where the string has pattern K*, by matching against ^(K)*$, we can get all tokens that match pattern K.
In the case where the string only has prefix that matches K*, by matching against ^(K)*, we can get all tokens that match pattern K.
This is the case in .NET regex, since it keeps all the captured text for a repeated capturing group.
However, since we are using Java, we don't have access to such feature.
3. Solution in Java
Checking that the string has the pattern K* can always be done with Matcher.matches()/String.matches(), since the engine will do full-blown backtracking on the input string to somehow "unify" K* with the input string. The hard thing is to split the input string into tokens that matches pattern K.
If K* is equivalent to K*+
If the pattern K has the property:
For all strings2, K* is equivalent to K*+, i.e. how the input string is split up into tokens that match pattern K is the same.
2 You can define this condition for only the input strings you are operating on, but ensuring this pre-condition is not easy. When you define it for all strings, you only need to analyze your regex to check whether the condition holds or not.
Then a one-pass solution that solves the problem can be constructed. You can repeatedly use Matcher.find() on the pattern \GK, and checks that the last match found is right at the end of the string. This is similar to your current solution, except that you do the boundary check with code.
The + after the quantifier * in K*+ makes the quantifier possessive. Possessive quantifier will prevent the engine from backtracking, which means each repetition is always the first possible match for the pattern K. We need this property so that the solution \GK has equivalent meaning, since it will also return the first possible match for the pattern K.
If K* is NOT equivalent to K*+
Without the property above, we need 2 passes to solve the problem. First pass to call Matcher.matches()/String.matches() on the pattern K*. On second pass:
If the string does not match pattern K*, we will repeatedly use Matcher.find() on the pattern \GK until no more match can be found. This can be done due to how we define which prefix string to take when the input string does not match pattern K*.
If the string matches pattern K*, repeatedly use Matcher.find() on the pattern \GK(?=K*$) is one solution. This will result in redundant work matching the rest of the input string, though.
Note that this solution is universally applicable for any K. In other words, it also applies for the case where K* is equivalent to K*+ (but we will use the better one-pass solution for that case instead).
Here is an additional answer to the already accepted one. Below is an example code snippet that only goes through the pattern once with m.find(), which is similar to your one pass solution, but will not parse non-matching lines.
import java.util.regex.*;
class test{
public static void main(String args[]){
String t = "<1><2><3>";
Pattern pat = Pattern.compile("(<\\d>)(?=(<\\d>)*$)(?<=^(<\\d>)*)");
Matcher m = pat.matcher(t);
while (m.find()) {
System.out.println("Matches!");
System.out.println(m.group());
}
}
}
The regex explained:
<\\d> --This is your k pattern as defined above
?= -- positive lookahead (check what is ahead of K)
<\\d>* -- Match k 0 or more times
$ -- End of line
?<= -- positive lookbehind (check what is behind K)
^ -- beginning of line
<\\d>* -- followed by 0 or more Ks
Regular expressions are beautiful things.
Edit: As pointed out to me by #nhahtdh, this is just an implemented version of the answer. In fact the implementation above can be improved with the knowledge in the answer.(<\\d>)(?=(<\\d>)*$)(?<=^(<\\d>)*) can be changed to \\G<\\d>(?=(<\\d>)*$).
Below is a one-pass solution using Matcher.start and Matcher.end.
boolean products(String products)
{
String regex = "<[0-9]>";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(products);
int lastEnd = 0;
while (matcher.find())
{
if (lastEnd != matcher.start())
return false;
System.out.println(matcher.group());
lastEnd = matcher.end();
}
if (lastEnd != products.length())
return false;
return true;
}
The only disadvantage is that it will print out (or process) all values prior to finding invalid data.
For example, products("<1><2>a<3>"); will print out:
<1>
<2>
prior to throwing the exception (because up until there the string is valid).
Either having this happen or having to store all of them temporarily seems to be unavoidable.
String t = "<1><2><3>";
Pattern pat = Pattern.compile("(<\\d>)*");
Matcher m = pat.matcher(t);
if (m.matches()) {
//String[] tt = t.split("(?<=>)"); // Look behind on '>'
String[] tt = t.split("(?<=(<\\d>))"); // Look behind on K
}
I have the following string:
http://xxx/Content/SiteFiles/30/32531a5d-b0b1-4a8b-9029-b48f0eb40a34/05%20%20LEISURE.mp3?&mydownloads=true
How can I extract the part after 30/? In this case, it's 32531a5d-b0b1-4a8b-9029-b48f0eb40a34.I have another strings having same part upto 30/ and after that every string having different id upto next / which I want.
You can do like this:
String s = "http://xxx/Content/SiteFiles/30/32531a5d-b0b1-4a8b-9029-b48f0eb40a34/05%20%20LEISURE.mp3?&mydownloads=true";
System.out.println(s.substring(s.indexOf("30/")+3, s.length()));
split function of String class won't help you in this case, because it discards the delimiter and that's not what we want here. you need to make a pattern that looks behind. The look behind synatax is:
(?<=X)Y
Which identifies any Y that is preceded by a X.
So in you case you need this pattern:
(?<=30/).*
compile the pattern, match it with your input, find the match, and catch it:
String input = "http://xxx/Content/SiteFiles/30/32531a5d-b0b1-4a8b-9029-b48f0eb40a34/05%20%20LEISURE.mp3?&mydownloads=true";
Matcher matcher = Pattern.compile("(?<=30/).*").matcher(input);
matcher.find();
System.out.println(matcher.group());
Just for this one, or do you want a generic way to do it ?
String[] out = mystring.split("/")
return out[out.length - 2]
I think the / is definitely the delimiter you are searching for.
I can't see the problem you are talking about Alex
EDIT : Ok, Python got me with indexes.
Regular expression is the answer I think. However, how the expression is written depends on the data (url) format you want to process. Like this one:
Pattern pat = Pattern.compile("/Content/SiteFiles/30/([a-z0-9\\-]+)/.*");
Matcher m = pat.matcher("http://xxx/Content/SiteFiles/30/32531a5d-b0b1-4a8b-9029-b48f0eb40a34/05%20%20LEISURE.mp3?&mydownloads=true");
if (m.find()) {
System.out.println(m.group(1));
}
I am wondering why the results of the java regex pattern.matcher() and pattern.matches() differ when provided the same regular expression and same string
String str = "hello+";
Pattern pattern = Pattern.compile("\\+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println("I found the text " + matcher.group() + " starting at "
+ "index " + matcher.start() + " and ending at index " + matcher.end());
}
System.out.println(java.util.regex.Pattern.matches("\\+", str));
The result of the above are:
I found the text + starting at index 5 and ending at index 6
false
I found that using an expression to match the full string works fine in case of matches(".*\\+").
pattern.matcher(String s) returns a Matcher that can find patterns in the String s. pattern.matches(String str) tests, if the entire String (str) matches the pattern.
In brief (just to remember the difference):
pattern.matcher - test if the string contains-a pattern
pattern.matches - test if the string is-a pattern
Matcher.find() attempts to find the next subsequence of the input sequence that matches the pattern.
Pattern.matches(String regex, CharSequence input) compiles the regex into a Matcher and returns Matcher.matches().
Matcher.matches attempts to match the entire region (string) against the pattern (Regex).
So, in your case, the Pattern.matches("\\+", str) returns a false since str.equals("+") is false.
From the Javadoc, see the if, and only if, the entire region section
/**
* Attempts to match the entire region against the pattern.
*
* <p> If the match succeeds then more information can be obtained via the
* <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p>
*
* #return <tt>true</tt> if, and only if, <b>the entire region</b> sequence
* matches this matcher's pattern
*/
public boolean matches() {
return match(from, ENDANCHOR);
}
So if your String was just "+", you'd get a true result.
matches tries to match the expression against the entire string. Meaning, it checks whether the entire string is a patern or not.
conceptually think it like this, it implicitly adds a ^ at the start and $ at the end of your pattern.
For, String str = "hello+", if you want matches() to return true, you need to have pattern like ".\+."
I hope this answered your question.
Pattern.matches is testing the whole String, in your case you should use:
System.out.println(java.util.regex.Pattern.matches(".*\\+", str));
Meaning any string and a + symbol
I think your question should really be "When should I use the Pattern.matches() method?", and the answer is "Never." Were you expecting it to return an array of the matched substrings, like .NET's Matches methods do? That's a perfectly reasonable expectation, but no, Java has nothing like that.
If you just want to do a quick-and-dirty match, adorn the regex with .* at either end, and use the string's own matches() method:
System.out.println(str.matches(".*\\+.*"));
If you want to extract multiple matches, or access information about a match afterward, create a Matcher instance and use its methods, like you did in your question. Pattern.matches() is nothing but a wasted opportunity.
Matcher matcher = pattern.matcher(text);
In this case, a matcher object instance will be returned which performs match operations on the input text by interpreting the pattern. Then we can use,matcher.find() to match no. of patterns from the input text.
(java.util.regex.Pattern.matches("\\+", str))
Here, the matcher object will be created implicitly and a boolean will be returned which matches the whole text with the pattern. This will work as same as the str.matches(regex) function in String.
The code equivalent to java.util.regex.Pattern.matches("\\+", str) would be:
Pattern.compile("\\+").matcher(str).matches();
method find will find the first occurrence of the pattern in the string.
Question closed because I misunderstood the situation. To show my stupidity though, I'll not remove what I wrote.
I'd like to encode a piece of string into Pattern, and get the string back.
I tried:
String s = buff.readLine();
Pattern p = new Pattern(s);
and use the following to retrieve my string
System.out.println(p.toString());
But it didn't work, the output is just the "package name#(some random things)... I tried Pattern p = Pattern.compile (s);
but I got an error from the compiler.
Well I just tried this:
Pattern p = Pattern.compile("Hello");
System.out.println( p.toString() );
And it worked, printing out 'Hello'.
Are you importing the java.util.regex.Pattern package?
The javadoc for Pattern#toString() seems to indicate that the source of the complete regex is only returned since java 1.5. However, Pattern#pattern() does not have a since tag, so it is presumably available since the class was introduced (java 1.4). Try System.out.println(p.pattern());
You're using a regex Pattern object to store and retrieve a String. This makes no sense. A Pattern is not used for storing Strings. A Pattern is used for searching other strings. It's a regular expression engine. Let me give you an example of the use of a Pattern.
We really have 2 objects when using Regular Expressions in Java. Pattern, and Matcher.
Pattern = A Regular Expression.
Matcher = All of the Matches found when we apply the Pattern to a String.
Let me give you an example of Pattern and Matcher, we'll search for four digits, separated by a colon, like as in time, ie 12:42
long timeL;
Pattern pattern = Pattern.compile(".*([1234567890]{2}:[1234567890]{2}).*");
Matcher matcher = pattern.matcher("Match me! 12:42 Match me!");
if (matcher.matches()) {
String timeStr = matcher.group(1);
System.out.println("Just the time: "+timeStr);
System.out.println("The entire String: "+matcher.group(0));
String[] timeParts = timeStr.split("[:]");
int hours = Integer.parseInt(timeParts[0]);
int minutes = Integer.parseInt(timeParts[1]);
timeL = (hours*60*60*1000) + (minutes*60*1000);
System.out.println(timeL);
}
After we've applied the Pattern to the String, and gotten a Matcher, we ask if the Matcher actually has a Match or not. You'll notice that we then request group 1, which is the match in the parantheses in: .([1234567890]{2}:[1234567890]{2}).
group 0 would be the entire match, and would result in returning the String given.
So, I hope you understand why it's extremely weird to be using a Pattern to store a String.