Java string start with number

Java Regex of String start with number and fixed length

To see the list of listening ports both UDP and TCP, complete with the program names: From another machine, you can use or a similar tool to see what ports are open/listening by scanning the IP address assigned to the dev box. It’s a Dev box and we have certain port ranges we are permitted for development use. .

Java Regex of String start with number and fixed length

I made a regular expression for checking the length of String , all characters are numbers and start with number e.g 123 Following is my expression

But it was unable to check the length of String. It validates those strings only their length is 9 and start with 123. But if I pass the String 1234567891 it also validates it. But how should I do it which thing is wrong on my side.

Like already answered here, the simplest way is just removing the + :

Depending on what you need exactly.

You can also use another, a bit more complicated and generic approach, a negative lookahead:

This: (. ) is a negative look-ahead ( ?= would be a positive look-ahead), it means that if the expression after the look-ahead matches this pattern, then the overall string doesn’t match. Roughly it means: The criteria for this regular expression is only met if the pattern in the negative look-ahead doesn’t match .

In this case, the string matches only if . doesn’t match, which means 10 or more characters, so it only matches if the pattern in front matches up to 9 characters.

A positive look-ahead does the opposite, only matching if the criteria in the look-ahead also matches.

Just putting this here for curiosity sake, it’s more complex than what you need for this.

I changed it to 6 because 1, 2, and 3 should probably still count as digits.

Also, I removed the + . With it, it would match 1 or more \d s (therefore an infinite amount of digits).

Based on your comment below Doorknobs’s answer you can do this:

int length = 9; String prefix = "123"; // or whatever String regex = "^" + prefix + "\\d< " + (length - prefix.length()) + ">$"; if (input.matches(regex)) < // good >else < // bad >

Advanced parsing of numeric ranges from string, I’m using Java to parse strings input by the user, representing either single numeric values or ranges. The user can input the following string: 10-19. And his intention is to use whole …

Bus Simulator 18 — 54 In the 18M Iveco

Route: Fishers Ground — Roman RoadBus: Iveco Urbanway 18M

What is the Simplest Form of a Ratio?

To learn more about Ratios, enroll in our full course now: https://infinitylearn.com/cbse-fullcourse?utm_source=YouTube&utm_medium=DME&utm_campaign=5J6wNdD8

How to find the first four terms of a sequence

👉 Learn how to find the first five terms of a sequence. Given an explicit formula for a sequence, we can find the nth term of the sequence by plugging the t

Читайте также:  Php object new stdclass

How to count how many vowels our String have? [duplicate]

I’m new in Java and I’m trying to solve a challenge. I have to write some words and to compare which one is longer, and how many vowels the longer one have. Also if you write «end», writing of words to end and to print something else, in our case You didn’t wrote any word .

Output Example in Terminal (CMD):

Write a word, or write ‘end’ to end writing: test
Write a word, or write ‘end’ to end writing: tee
Write a word, or write ‘end’ to end writing: testing
Write a word, or write ‘end’ to end writing: end

Word testing is longest and it have 2 vowels.

Output Example if you don’t write any word:

Write a word, or write ‘end’ to end writing:
Write a word, or write ‘end’ to end writing:
Write a word, or write ‘end’ to end writing: end

You didn’t wrote any word.

Program should be coded using Scanner (Input) , Switch Case and Do While . Strings should be compared using method equalsIgnoreCase() .

I tried many times, and what I did is only writing and deleting code.

This is my code:

import java.util.Scanner; public class VowelFinder < public static void main(String[] args) < Scanner scan = new Scanner(System.in); String word = null; int num = 0; String max = null; final String SENTINEL = "end"; System.out.println(" "); do < System.out.print("Write a word, or write `" + SENTINEL + "` to end writing: "); word = scan.nextLine(); if(!word.equalsIgnoreCase(SENTINEL)) < int nr = countVowels(word); if (num > > while (!word.equalsIgnoreCase(SENTINEL)); if (max != null) < System.out.println(" "); System.out.println("Word `" + max + "` is longest word, and countains " + num + " vowels."); >else < System.out.println(" "); System.out.println("You din't wrote any word !"); >> private static int countVowels(String word) < int counter = 0; int vowels = 0; while(counter < word.length())< char ch = word.charAt(counter++); switch (ch) < //Lower Case case 'a': case 'e': case 'i': case 'o': case 'u': case 'y': //Upper Case case 'A': case 'E': case 'I': case 'O': case 'U': case 'Y': vowels++; default: // do nothing >> return vowels; > > 

When I do so in terminal (CMD)

Write a word, or write ‘end’ to end writing:
Write a word, or write ‘end’ to end writing:
Write a word, or write ‘end’ to end writing: end

It prints me Word ‘ ‘ is longest word, and countains 0 vowels. , but it should print You didn’t wrote any word.

Can someone help me ? Where I did wrong ?

It should print me You didn’t wrote any word if I don’t write any word.

I hope I was clear and you can help me. If I wasn’t clear please ask me.

Thanks for your contribution.

change the if condition to

if (word != null && !»».equals(word.trim()) && !word.equalsIgnoreCase(SENTINEL))

I added a null check and did a trim to remove the white spaces.

I have made some changes and it worked for me.

if (max != null && !max.trim().isEmpty() && max.length()>0)

You could check in countVowels() whether the current word is nothing.

private static int countVowels(String word) < int counter = 0; int vowels = 0; if(word.length() == 0)< return -1; >. > 

The return value is less than 0 so max won’t be replaced.

Simplifying a Fraction-Advanced: Worksheet 5, · PDF file4. Write the fraction 14/42 in simplest form. 5. Write the fraction 18/54 in simplest form. 6. Write the fraction 22/55 in simplest form. 7. Write the fraction 17/51 in simplest form. 8. Write the …

How can I find available but unoccupied ports on a Linux box?

It’s a Dev box and we have certain port ranges we are permitted for development use. . unfortunately, getting a tech’s attention to find out what ports are available is like pulling teeth. Would prefer a script or alias that does this so that we don’t have to ask all the time. Clues? Is this an iptables command or is it a netstat command or some weird combo? nmap is not available on this machine.

Читайте также:  Java cast collection to list

Please don’t say this is a Server Fault question. They say it’s a programming question. 😐

Definitely a SF question but here we go. From the dev box itself (command line) you should be able to see what ports are in use with the netstat tool.

To see the list of listening ports both UDP and TCP, complete with the program names:

# preferably as root netstat --listening --program --numeric-ports --protocol=ip -6 -4 

From another machine, you can use nmap or a similar tool to see what ports are open/listening by scanning the IP address assigned to the dev box. Before trying this, maybe you should ask for permission. Also, you should consider that the box in question might have firewall rules in place that can thwart your scanning attempts.

To see what firewall rules are in place in the dev box try:

# as root iptables -nvxL -t filter # maybe there are NAT rules, redirects to other addresses, etc. iptables -nvxL -t nat 

To see what these iptables options do, try man iptables .

As an example, assuming 172.16.0.1 is the IP address assigned to the dev box, to run nmap in the simplest way possible:

# preferably as root nmap -v 172.16.0.1 

In a few minutes you should see a list of ports/services listening in that relevant box. Try man nmap and read the documentation for more details.

If you really think this is a programming issue, you can use the netcat tool and program a simple script to do something roughly equivalent to what nmap does.

#!/bin/bash # # DISCLAIMER: NOT TESTED -- just an example # NOTE: This will take many DAYS to complete HOST=172.16.0.1 for port in `seq 1 65535` do echo "Trying $. " netcat -vvv $ $port -w 1 -z done 

For every open TCP port you should see a line similar to this:

Connection to 172.16.0.1 23 port [tcp/telnet] succeeded! 

Newest ‘delphi’ Questions, Delphi is a language for rapid development of native Windows, macOS, Linux, iOS, and Android applications through use of Object Pascal. The name refers to the Delphi …

How to use Java 8 Streams to pull a string value out of a list of objects and create a new list?

I just can’t seem to figure this one out after looking at all kinds of examples.

Here’s what I’m doing right now:

HashSet oldIds = new HashSet<>(); HashSet newIds = new HashSet<>(); for (Release currentRelease: lastPage.getPage()) < oldIds.add(currentRelease.getId()); >for (Release currentRelease: lastPageAgain)

I know there’s a much better way to ‘collect’ these values into the HashSet:

lastPage.getPage().getContent().stream().collect(release::getId()); 

But that doesn’t compile unfortunately.

1) release is not a variable here.
You have to reference the Release class in the method reference.

2) method references have not to specify the parenthesis for the method as you did here : release::getId() .
A method reference refers always to a method.
So () is indeed implicit.
Besides, a method reference may refer to a method that has parameter(s).
So specifying () would be so error prone too.

Just replace release::getId() by release::getId .

3) collect() cannot accept a function such as release::getId() .
In its simplest overload form, it expects to have a Collector . So pass Collectors.toSet() as argument.

You can simply use map() to map something to something else.
Note that you should favor Set to HashSet in your code.
Programming by interface improves the maintainability of your code.
Collectors.toSet() follows this principle. So it returns a Set declared type.

Set oldIds = lastPage.getPage().getContent() .stream() .map(Release::getId).collect(Collectors.toSet()); 

And do the same thing for newIds .

 HashSet oldIds = new HashSet<>(); HashSet newIds = new HashSet<>(); lastPage.getPage().getContent().forEach(r -> oldIds.add(r.getId())); // my first lambda :) lastPageAgain.forEach(r -> newIds.add(r.getId())); 

The syntax is slightly different because lastPage and lastPageAgain are actually different types.

Читайте также:  Php pdo where and

Bubble Sort Algorithm, Time Complexity: O(N 2) Auxiliary Space: O(1) Worst Case Analysis for Bubble Sort: The worst-case condition for bubble sort occurs when elements of the array are arranged in …

Источник

Java Regex of String start with number and fixed length

But it was unable to check the length of String. It validates those strings only their length is 9 and start with 123. But if I pass the String 1234567891 it also validates it. But how should I do it which thing is wrong on my side.

The word validate better describes what you’re trying to accomplish. You’re trying to validate the length of the string to contain exactly 9 digits after the prefix «123».

3 Answers 3

Like already answered here, the simplest way is just removing the + :

Depending on what you need exactly.

You can also use another, a bit more complicated and generic approach, a negative lookahead:

This: (. ) is a negative look-ahead ( ?= would be a positive look-ahead), it means that if the expression after the look-ahead matches this pattern, then the overall string doesn’t match. Roughly it means: The criteria for this regular expression is only met if the pattern in the negative look-ahead doesn’t match.

In this case, the string matches only if . doesn’t match, which means 10 or more characters, so it only matches if the pattern in front matches up to 9 characters.

A positive look-ahead does the opposite, only matching if the criteria in the look-ahead also matches.

Just putting this here for curiosity sake, it’s more complex than what you need for this.

Источник

Determine if a string starts with a number in Java

This post will check if a string starts with a number or not in Java.

1. Naive solution

A naive solution is to extract the first character from the given string using the charAt() method and validate that character falls under the numeric ASCII range or not.

2. Using Character.isDigit() method

The recommended solution is to use the Character.isDigit(char) method to check if the first character of the string is a digit or not. Note that this also supports all Unicode digits.

3. Using Regex

Another plausible way of determining whether a string ends with a number or not is using regex. This approach is not recommended as regular expressions are extremely slow.

Note that all the above solutions assume that the string is not empty. If the string is empty, the program will throw a StringIndexOutOfBoundsException .

That’s all about checking if a string starts with a number in Java.

Average rating 4.6 /5. Vote count: 10

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂

This website uses cookies. By using this site, you agree to the use of cookies, our policies, copyright terms and other conditions. Read our Privacy Policy. Got it

Источник

Оцените статью