I think you need to do something like pattern match. Example:
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
Then
if(b)
{
//Your code.
}
From @yshavit comments (which are important):
Worth noting that the Pattern p object is immutable and thread-safe, and can be shared (e.g. by creating the Pattern once and storing it in a private static final). If you don't care about creating the Pattern each time, and you don't need access to captured groups in the regex, you can also just call the static Pattern.matches(pattern, stringToLookIn)
Answer from kosa on Stack OverflowI think you need to do something like pattern match. Example:
Pattern p = Pattern.compile("a*b");
Matcher m = p.matcher("aaaaab");
boolean b = m.matches();
Then
if(b)
{
//Your code.
}
From @yshavit comments (which are important):
Worth noting that the Pattern p object is immutable and thread-safe, and can be shared (e.g. by creating the Pattern once and storing it in a private static final). If you don't care about creating the Pattern each time, and you don't need access to captured groups in the regex, you can also just call the static Pattern.matches(pattern, stringToLookIn)
If input is String, then you can use input.matches("[a-kA-K]+").
Documentation: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#matches(java.lang.String)
regex - Search "if condition" in .java file - Stack Overflow
if then condition using regex in java - Stack Overflow
java - If conditions using regex - Stack Overflow
java - understanding regex if then statements - Stack Overflow
Short answer: Regex doesn't work like that.
What you can do however, is to use two separate patterns to validate:
\"[^\"]+?\" :.*
To check the one that can contain special characters, and:
[a-zA-Z]+? :.*
To check the one that can't
EDIT:
Thinking some more about it, you could combine the two patterns above like so:
^(\"[^\"]+?\"|[a-zA-Z]+?) :.*$
Which will match something :"something" and "some-thing" :"something" but not "some-thing : "something" or some-thing : "something". Assuming that the string only contains the given text.
If I understand your question right, this simple regex should work
\"string1\" :\"string2\"
There is no conditionals in Java regexp, but you can simulate them by writing two expressions that include mutually exclusive look-behind constructs, like this:
((?<=if )then)|((?<!if )end)
This expression will match "then" when it is preceded by an "if "; it will match "end" when it is not preceded by an "if "
The Javadoc for java.util.regex.Pattern mentions, in its list of "Perl constructs not supported by this class":
- The conditional constructs
(?(condition)X)and(?(condition)X|Y).
So, no dice. But you should look through the Javadoc to see if you can achieve what you need by using regex features that it does support. (Or, if you post some more detailed examples, we can try to help.)
4 lines of code compared with 16 lines? Never mind which runs faster, the 4 line version is more efficient to write, more efficient to maintain.
If you have some code and have benchmarked it and identified a specific bottleneck then maybe consider making it more complicated, otherwise go with the simpler version every time.
Just use startsWith. Regex is a bit overkill, unless you want to accept String with leading spaces.
startsWith can work with "test" or even "testfoo". If you mean that "foo" can appear anywhere in the input after "test" (i.e. "testokokokfoonothing"), then regex should be used here.
Your code for regex version can be shortened to:
for (String line: ArrayList){
if (line.matches("^test.*") {
doSomething();
}
}
matches() check if the whole input matches the regex, so a bit of modification to the regex is necessary. The code above is slightly slower, since the Pattern is recompiled.
You can try the following regular expression:
(?:^|\s)if(?:\s)

Explanation of the regular expression:
NODE EXPLANATION
------------------------------------------------------------
(?: group, but do not capture:
------------------------------------------------------------
^ the beginning of the line
------------------------------------------------------------
| OR
------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
------------------------------------------------------------
) end of grouping
------------------------------------------------------------
if 'if'
------------------------------------------------------------
(?: group, but do not capture:
------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
------------------------------------------------------------
) end of grouping
This will match if preceded only by whitespace:
^\s*if\b
^ - anchor to beginning of line.
\s* - match zero or more whitespace characters (including spaces and tabs).
\b - require a word boundary. So it won't match iffy, etc.
A regex cannot perfectly identify a keyword in a programming language (as a completely correct solution requires fully parsing the language). However, this should capture if statements pretty well in code that follows typical style.
The syntax is correct. The strange looking (?....) sets up a conditional. This is the regular expression syntax for an if...then statement. The (1) is a back-reference to the capture group at the beginning of the regex, which matches an html <a> tag, if there is one since that capture group is optional. Since the back-reference to the captured tag follows the "if" part of the regex, what it is doing is making sure that there was an opening <a> tag captured before trying to match the closing one. A pretty clever way of making both tags optional, but forcing both when the first one exists. That's how it's able to match all the lines in the sample text even though some of them just have <img> tags.
As to why it throws an exception in your case, most likely the flavor of regex you're using doesn't support conditionals. Not all do.
EDIT: Here's a good reference on conditionals in regular expressions: http://www.regular-expressions.info/conditional.html
What you're looking at is a conditional construct, as Bryan said, and Java doesn't support them. The parenthesized expression immediately after the question mark can actually be any zero-width assertion, like a lookahead or lookbehind, and not just a reference to a capture group. (I prefer to call those back-assertions, to avoid confusion. A back-reference matches the same thing the capture group did, but a back-assertion just asserts that the capture group matched something.)
I learned about conditionals when I was working in Perl years ago, but I've never missed them in Java. In this case, for example, a simple alternation will do the trick:
(?i)<a\s+[^>]+>\s*<img\s+[^>]+>\s*</a]>|<img\s+[^>]+>
One advantage of the conditional version is that you can capture the IMG tag with a single capture group:
(?i)(<a\s+[^>]+>\s*)?(<img\s+[^>]+>)(?(1)\s*</a>)
In the alternation version you have to have a capturing group for each alternative, but that's not as important in Java as it is in Perl, with all its built-in regex magic. Here's how I would pluck the IMG tags in Java:
Pattern p = Pattern.compile(
"<a\\s+[^>]+>\\s*(<img\\s+[^>]+>)\\s*</a>|(<img\\s+[^>]+>)"
Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(s);
while (m.find())
{
System.out.println(m.start(1) != -1 ? m.group(1) : m.group(2));
}
Hi! I have an upcoming assignment and I’m not quite sure how to do it. I can’t find anything helpful on stackoverflow either, therefore I’m asking for help here. Basically, I have to make an if-statement that checks that the user uses the correct format for a regnumber; ”ABC123”. How can I make sure that the user uses three letters and then three numbers?
Thankful for any help!:)
A simplistic solution for that would be to use "look around"s, as specified in comments.
You can also use an actual URL object to do that if, as I imagine, you're working with actual URLs.
For instance:
String[] input = { "http://www.google.com", "http://foo.com", "www.foo.com" };
Pattern p = Pattern.compile("(?<=http).*(?=www)");
for (String s : input) {
Matcher m = p.matcher(s);
System.out.printf("Found in %s? %b%n", s, m.find());
try {
URL u = new URL(s);
System.out.printf("Authority starts with www and protocol is http for %s? %b%n", s,
u.getAuthority().startsWith("www") && u.getProtocol().equals("http"));
}
catch (MalformedURLException mue) {
System.out.printf("%s is not interpreted as well-formed URL.%n", s);
}
}
Output
Found in http://www.google.com? true
Authority starts with www and protocol is http for http://www.google.com? true
Found in http://foo.com? false
Authority starts with www and protocol is http for http://foo.com? false
Found in www.foo.com? false
www.foo.com is not interpreted as well-formed URL.
Effectively, your String should start with either http or www.
You don't care if http is followed by www. All you care about is your string should always start with *http8 or www and nothing else.
So,
public static void main(String[] args) {
String s1 = "http://www.google.com";
String s2 = "www.google.com";
String s3 = "sdfwww.google.com";
System.out.println(s1.matches("^(http|www).*"));
System.out.println(s2.matches("^(http|www).*"));
System.out.println(s3.matches("^(http|www).*"));
}
O/P ::
true
true
false
There are no conditionals in Java regexes.
I want a regex that checks if there are the same amount of regex's at the end as there are in the beginning. The conditional part: If there are x's at the beginning, then check if there are that many at the end, if there are then it is a match.
This may or may not be solvable. If you want to know if a specific string (or pattern) repeats, that can be done using a back reference; e.g.
^(\d+).+\1$
will match a line consisting of an arbitrary number digits, any number of characters, and the same digits matched at the start. The back reference \1 matches the string matched by group 1.
However if you want the same number of digits at the end as at the start (and that number isn't a constant) then you cannot implement this using a single (Java) regex.
Note that some regex languages / engines do support conditionals; see the Wikipedia Comparison of regular-expression engines page.
I would like to use split which accept regex like so :
String[] split = nums.split("\\s+"); // ["42", "36", "23827"]
If you want to use Pattern with Matcher, then you can use String \b\d+\b with word boundaries.
String regex = "\\b\\d+\\b";
By using word boundaries, you will avoid cases where the number is part of the word, for example "123 a4 5678 9b" you will get just ["123", "4578"]