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 Overflow
🌐
Coderanch
coderanch.com › t › 570241 › java › match-regular-expression
how to match the regular expression using if (Java in General forum at Coderanch)
March 13, 2012 - So your insistence on using an if-statement just makes no sense at all, since that has nothing to do with matching a regex. ... vijayalakshmi deepika wrote:i want to code in java using if conditional statement and match the regular expression and get the output of first string alone as Java.but ...
Discussions

regex - Search "if condition" in .java file - Stack Overflow
I want to search all if conditions in .java file. I am using BufferedReader to read file and pattern to search condition. My program searching all if but when my file look this: // if{} I get bad More on stackoverflow.com
🌐 stackoverflow.com
if then condition using regex in java - Stack Overflow
I have a pattern which goes like this String1 :"String2", i have to validate this pattern. here if u see there are two cases, the somestring1 can contain special characters if it is given within d... More on stackoverflow.com
🌐 stackoverflow.com
java - If conditions using regex - Stack Overflow
What regex would help satisfy the following situation: if (string starts with a letter (one or more)) it must be followed by a . or _ (not both) else no match Example (imagine i have a list of More on stackoverflow.com
🌐 stackoverflow.com
java - understanding regex if then statements - Stack Overflow
I'm trying really hard for them to allow java code functionality instead of pure regex for more versatile options. So to summarize, is there even a if/then option in regex and if so how is it formatted for what I'm trying to accomplish? EDIT: The string that I want to be the "if condition" is like this: if view_large string exists and is not null then capture the exact string 500/ which is captured within the catch all group I used... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 9484567 › regex-for-if-condition-in-java › 9485661
regex for if condition in java - Stack Overflow
February 28, 2012 - You will either have to do something outside of the regex (e.g. capture no and the text after it into a single group and split it with regular string functions outside of regex), or choose the capturing group from which to take the yes/no text depending on a condition. Either way, you need external code. Regular expressions have a certain expressive power and not everything may be expressed with their help. For example expressions as simple as "n A-characters followed by n B-characters" or "arithmetic expression with correct nesting of parentheses" are not possible to express using regex. If this was a practical task, I would suggest not using regex at all, but rather splitting the input string on first N spaces and validating each part separately using normal code.
🌐
Stack Overflow
stackoverflow.com › questions › 10888742 › if-conditions-using-regex
java - If conditions using regex - Stack Overflow
2012-06-05T14:50:25.53Z+00:00 ... if (string starts with a letter (one or more)) it must be followed by a . or _ (not both) else no match ... The regex is made to spec (you do not say anything about what is allowed to follow).
Find elsewhere
🌐
Regex101
regex101.com › r › hP7hM9 › 1 › codegen
regex101: If-Then-Else Conditionals
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String[] args) { final String regex = "(a)?b(?(1)c|d)"; final String string = "matches bd and abc. It does not match bc, but does match bd in abd. Let's see how this regular expression works on each of these four subject strings.\n" + "If-Then-Else Conditionals in Regular Expressions\n" + "http://www.regular-expressions.info/conditional.html"; final String subst = "\\1"; final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); final Matcher matcher = pattern.matcher(string); // The substituted value will be contained in the result variable final String result = matcher.replaceAll(subst); System.out.println("Substitution result: " + result); } } Please keep in mind that these code samples are automatically generated and are not guaranteed to work.
Top answer
1 of 4
3

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

2 of 4
3

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));
}
🌐
Stack Overflow
stackoverflow.com › questions › 49122557 › regex-to-define-if-statements
java - Regex to define if statements - Stack Overflow
Regexes aren't the way to do this. You should give ANTLR4 a try. ... The meeting that changed how we build software (Ep. 579) 2023 Developer Survey results are in: the latest trends in technology and... ... Does the policy change for AI-generated content affect users who (want to)...
🌐
Stack Overflow
stackoverflow.com › questions › 61454882 › how-to-use-regex-for-verifying-multiple-conditions-in-java
How to use regex for verifying multiple conditions in JAVA? - Stack Overflow
April 27, 2020 - About the length of the string, I don't see a good way to check that in a regular expression. So just check it with an if-else statement.
🌐
Vogella
vogella.com › tutorials › JavaRegularExpressions › article.html
Regular expressions in Java - Tutorial
For example, the following will match "a" if "a" is not followed by "b". ... You can add the mode modifiers to the start of the regex. To specify multiple modes, put them together as in (?ismx). ... (?m) for "multi-line mode" makes the caret and dollar match at the start and end of each line in the subject string. The backslash \ is an escape character in Java Strings.
🌐
Rexegg
rexegg.com › regex-conditionals.php
Conditional Regular Expressions—from 101 to Advanced
✽ (?(A)|X) amounts to saying "if proposition A is not true, then match pattern X." If you translate the IF…THEN…ELSE construction literally, it says "if proposition A is true, then match the empty string (which always matches at every position), otherwise match pattern X." Proposition A Proposition A can be one of several kinds of assertions that the regex engine can test and determine to be true or false. These various kinds of assertions are expressed by small variations in the conditional syntax.
🌐
W3Schools
w3schools.com › java › java_regex.asp
Java Regular Expressions
Java does not have a built-in Regular Expression class, but we can import the java.util.regex package to work with regular expressions.
🌐
Reddit
reddit.com › r/javahelp › how do i check a regnr with an if-statement?
r/javahelp on Reddit: How do I check a regnr with an if-statement?
November 17, 2021 -

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!:)

Top answer
1 of 2
4
I don't know if there are any constraints for your assignment, but usually you would use a regular expression for that. Read up on this in the javadoc for the Pattern class. https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
2 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
Top answer
1 of 4
1

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.
2 of 4
1

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