Saturday, 5 April 2025

Java Regex Tutorial (With Examples)

 

Java Regex Tutorial (With Examples)

✅ What is Regex?

Regex (short for Regular Expression) is a sequence of characters that defines a search pattern. It is widely used for string pattern matching, validations, and data parsing.

In Java, regex is supported by the java.util.regex package.


Key Classes in Java Regex

  • Pattern: A compiled representation of a regular expression.

  • Matcher: An engine that performs match operations on a character sequence using a Pattern.


Basic Example



import java.util.regex.*;


public class RegexDemo {

    public static void main(String[] args) {

        Pattern pattern = Pattern.compile("Java");

        Matcher matcher = pattern.matcher("Java is fun");


        boolean matchFound = matcher.find();

        System.out.println("Match found? " + matchFound);  // Output: true

    }

}






Common Regex Patterns

Pattern

Meaning

Example Match

.

Any character

"a", "1", "#"

\d

Any digit (0-9)

"3", "9"

\w

Any word char (a-z, A-Z, 0-9, _)

"a", "Z", "3", "_"

\s

Whitespace

" " (space), \t

*

0 or more

"a*", "", "aaa"

+

1 or more

"a+", "aaa"

?

0 or 1

"a?", "", "a"

[]

Character set

"[aeiou]" matches any vowel

^

Starts with

"^Java" matches "Java is..."

$

Ends with

"end$" matches "The end"


Examples

✅ 1. Check if a string contains digits



String input = "My phone number is 12345";

boolean hasDigits = input.matches(".*\\d+.*");

System.out.println(hasDigits); // true



✅ 2. Validate email address



String email = "test@example.com";

boolean isValid = email.matches("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,6}$");

System.out.println(isValid); // true



✅ 3. Extract numbers from a string



String input = "Order123, Invoice456";

Pattern pattern = Pattern.compile("\\d+");

Matcher matcher = pattern.matcher(input);


while (matcher.find()) {

    System.out.println("Found number: " + matcher.group());

}



✅ 4. Replace all whitespaces



String messy = "Java   is \t awesome!";

String cleaned = messy.replaceAll("\\s+", " ");

System.out.println(cleaned); // Java is awesome!



✅ 5. Validate phone number (e.g., US format)



String phone = "123-456-7890";

boolean isValid = phone.matches("\\d{3}-\\d{3}-\\d{4}");

System.out.println(isValid); // true



Bonus: Pattern Flags

You can make patterns case-insensitive:



Pattern pattern = Pattern.compile("java", Pattern.CASE_INSENSITIVE);

Matcher matcher = pattern.matcher("I love Java");

System.out.println(matcher.find()); // true



Tips for Automation Testers:

  • Use regex in assertions with API responses.

  • Clean dynamic values from logs before validation.

  • Validate formats (email, timestamp, ID) using .matches().


Practice Exercise for You:

  1. Write a regex to validate dates in format dd/mm/yyyy.

  2. Extract all words starting with capital letters from a paragraph.

  3. Replace all HTML tags with an empty string (basic HTML cleanup).

Sunday, 23 March 2025

Remove All Occurrences of a Given Character using Two Pointer Approach

 



- 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤&𝗔 𝗣𝗮𝗰𝗸𝗮𝗴𝗲 𝗳𝗼𝗿 𝗧𝗲𝘀𝘁 𝗔𝘂𝘁𝗼𝗺𝗮𝘁𝗶𝗼𝗻 & 𝗦𝗗𝗘𝗧: https://topmate.io/sidharth_shukla/605319



Problem: Remove All Occurrences of a Given Character

Problem Statement:

Given a string s and a character ch, remove all occurrences of ch from s using the two-pointer approach.

Example 1:

Input: "apple", 'p'
Output: "ale"

Example 2:

Input: "banana", 'a'
Output: "bnn"


Java Solution (Two-Pointer Approach)

public class RemoveCharacter {
public static String removeChar(String s, char ch) { char[] chars = s.toCharArray(); int j = 0; // Pointer for placing valid characters for (int i = 0; i < chars.length; i++) { if (chars[i] != ch) { chars[j] = chars[i]; j++; // Move valid character index forward } } return new String(chars, 0, j); } public static void main(String[] args) { System.out.println(removeChar("apple", 'p')); // Output: "ale" System.out.println(removeChar("banana", 'a')); // Output: "bnn" } }

Explanation (Two-Pointer Approach)

  1. Use Two Pointers:

    • i iterates through the original string.
    • j keeps track of the next position for valid characters.
  2. Skip the Character to Remove:

    • If s[i] is not equal to ch, move it to j position.
  3. Return New String Without the Removed Characters.

Time Complexity: O(n) (single pass through the string)
Space Complexity: O(n) (output string storage)

🔥 This is an easy and efficient way to remove a character from a string using two pointers! 🚀



*** - 𝗝𝗮𝘃𝗮 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤&𝗔 𝗣𝗮𝗰𝗸𝗮𝗴𝗲: https://topmate.io/sidharth_shukla/1170024 - Learn Test Automation with 1:1 Guidance & Interview Preparation: https://lnkd.in/giCxnJJ7. HOLI Discount: Use Code 𝗦𝗜𝗗𝗛𝗔𝗥𝗧𝗛𝟭𝟬 to get 10% Discount (ONLY for first 10 enrollments): https://lnkd.in/giCxnJJ7 ****

Friday, 21 March 2025

Rearrange String: Move Vowels to the Beginning While Keeping Order

 


Problem Statement

Given a string s, rearrange the characters such that all vowels appear at the beginning, while maintaining the relative order of the consonants. The order of vowels should also remain the same as in the original string.

Example 1

Input: "automation"
Output: "auaotmtn"

Example 2

Input: "hello"
Output: "eo hll"

Example 3

Input: "java"
Output: "aa jv"


Solution Approach

  1. Extract vowels in order.

  2. Extract consonants in order.

  3. Concatenate vowels + consonants to form the result.


You can find the video here

Java Solution


public class MoveVowelsToLeft {

    public static String moveVowelsToLeft(String s) {

        StringBuilder vowels = new StringBuilder();

        StringBuilder consonants = new StringBuilder();

        

        for (char c : s.toCharArray()) {

            if (isVowel(c)) {

                vowels.append(c);

            } else {

                consonants.append(c);

            }

        }

        return vowels.append(consonants).toString();

    }


    private static boolean isVowel(char c) {

        return "AEIOUaeiou".indexOf(c) != -1;

    }


    public static void main(String[] args) {

        System.out.println(moveVowelsToLeft("automation")); // Output: auaotmtn

        System.out.println(moveVowelsToLeft("hello"));      // Output: eo hll

        System.out.println(moveVowelsToLeft("java"));       // Output: aa jv

    }

}



Time Complexity Analysis

  • O(n), where n is the length of the string (single pass to classify characters, another pass to concatenate).



- 𝗝𝗮𝘃𝗮 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤&𝗔 𝗣𝗮𝗰𝗸𝗮𝗴𝗲: https://topmate.io/sidharth_shukla/1170024 - Learn Test Automation with 1:1 Guidance & Interview Preparation: https://lnkd.in/giCxnJJ7. HOLI Discount: Use Code 𝗦𝗜𝗗𝗛𝗔𝗥𝗧𝗛𝟭𝟬 to get 10% Discount (ONLY for first 10 enrollments): https://lnkd.in/giCxnJJ7 - 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤&𝗔 𝗣𝗮𝗰𝗸𝗮𝗴𝗲 𝗳𝗼𝗿 𝗧𝗲𝘀𝘁 𝗔𝘂𝘁𝗼𝗺𝗮𝘁𝗶𝗼𝗻 & 𝗦𝗗𝗘𝗧: https://topmate.io/sidharth_shukla/605319

Sunday, 16 March 2025

9 tips to get your LinkedIn job ready for MAANG

 Follow some steps below for your linkedin :


Here are 9 tips to get your LinkedIn job ready:




1) High Quality Profile Picture

 ↳ Pick a recent smiling headshot where the face is clearly visible.

 ↳ Use websites like PFPMaker to generate professional looking photo.

 ↳ Use Photofeeler website to get feedback


2) Write a killer headline

 ↳ One sentence to show the value you bring to the future employer

 ↳ Avoid using buzzwords like Motivated, Skilled, Leader

 ↳ Follow a template like [Role][Skills][Interest & Value Proposition]

 ↳ Working Professional Example: Data Scientist @ ABC | Python, PyTorch | Helping hospitals reduce their ML training cost

 ↳ Student Example: Pursuing Computer Science @ ABC | JavaScript, Node.js | Web Development


3) Custom LinkedIn URL

 ↳ The default url to your LinkedIn profile may not be very readable.

 ↳ Change it to something that includes your name.


4) Write a killer About section

 ↳ A short paragraph that speaks of your professional journey.

 ↳ Write case studies that showcase specific results.

 ↳ Use right keywords as it can boost your visibility to recruiters and hiring managers.


5) Skills Matter

 ↳ Linked ranks you based on the skills you put.

 ↳ Add 5 most relevant skills

 ↳ Only skills with endorsements will count

 ↳ Ask colleagues, friends, family & classmates for endorsement (aim for 5)


6) Leverage your Featured Section

 ↳ Showcase the most important work you have done.

 ↳ Add portfolio website, GitHub links, LinkedIn post or anything else you are proud of.


7) Fill your experience and education section

 ↳ Add up to date work experience and location

 ↳ Write bullet points for the projects you worked on.

 ↳ Include relevant keywords and technologies you worked with.

 ↳ Add your education history

 ↳ Include projects, links and relevant certifications


8) Engage and support Others

 ↳ Adding a valuable comment can generate tons of profile views.

 ↳ Support others in their job search journey.

 ↳ Leave an overall positive impression which help others grow.


9) Create Content

 ↳ Content is networking at scale.

 ↳ Your one post can reach more people than your entire connection base.

 ↳ It can increase your visibility and bring in more opportunities.

Monday, 3 March 2025

𝗖𝗿𝗮𝗰𝗸𝗶𝗻𝗴 𝗦𝗗𝗘𝗧 𝗖𝗼𝗱𝗶𝗻𝗴 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲𝘀 — 𝗟𝗲𝘁’𝘀 𝗠𝗮𝗸𝗲 𝗜𝘁 𝗘𝗮𝘀𝘆!

 





All Time Popular Posts

Most Featured Post

Java Regex Tutorial (With Examples)

  Java Regex Tutorial (With Examples) ✅ What is Regex? Regex (short for Regular Expression ) is a sequence of characters that defines a sea...