How to match all numerical characters and some single characters using regex - java

How can I match all numbers along with specific characters in a String using regex? I have this so far
if (!s.matches("[0-9]+")) return false;
I don't understand much regex, but this matches all characters from 0-9 and now I need to be able to match other specific characters, for example "/", ":", "$"

You can use this regex by including those symbols in a character class:
s.matches("[0-9$/:]+")
Read more about character class

You can add the other characters that you need to match to the end of the character group, like this:
if (!s.matches("[0-9/:$]+")) return false;
You need to be careful about several things:
If ^ is among the characters, it must not be the first one of the group
If - is among the characters, it must be the last one in the group
If ] is among the characters, it needs to be escaped for regex and for Java, e.g. [\\]]
If \ is among the characters, it needs to be escaped for regex and for Java, e.g. [\\\\]

Regex:
String regex = "\\d/:$+";

Related

Regex-How to prevent repeated special characters?

I don't have an experience on Regular Expressions. I need to a regular expression which doesn't allow to repeat of special characters (+-*/& etc.)
The string can contain digits, alphanumerics, and special characters.
This should be valid : abc,df
This should be invalid : abc-,df
i will be really appreciated if you can help me ! Thanks for advance.
Two solutions presented so far match a string that is not allowed.
But the tilte is How to prevent..., so I assume that the regex
should match the allowed string. It means that the regex should:
match the whole string if it does not contain 2
consecutive special characters,
not match otherwise.
You can achieve this putting together the following parts:
^ - start of string anchor,
(?!.*[...]{2}) - a negative lookahead for 2 consecutive special
characters (marked here as ...), in any place,
a regex matching the whole (non-empty) string,
$ - end of string anchor.
So the whole regex should be:
^(?!.*[!##$%^&*()\-_+={}[\]|\\;:'",<.>\/?]{2}).+$
Note that within a char class (between [ and ]) a backslash
escaping the following char should be placed before - (if in
the middle of the sequence), closing square bracket,
a backslash itself and / (regex terminator).
Or if you want to apply the regex to individual words (not the whole
string), then the regex should be:
\b(?!\S*[!##$%^&*()\-_+={}[\]|\\;:'",<.>\/?]{2})\S+
[\,\+\-\*\/\&]{2,} Add more characters in the square bracket if you want.
Demo https://regex101.com/r/CBrldL/2
Use the following regex to match the invalid string.
[^A-Za-z0-9]{2,}
[^\w!\s]{2,} This would be a shortest version to match any two consecutive special characters (ignoring space)
If you want to consider space, please use [^\w]{2,}

How to use regex in matches() to look for letters, dots, and apostrophe?

In the following code, I tried many expressions to check if the string str has only letters, dots, or apostrophe by using matches() method.
However, it's not returning true for this string, for example, one o'clock. :
String str = "One o'clock.";
System.out.println(str.matches("[^a-zA-Z'. ]"));
You have two problems:
your regex is using negated character class [^...]
your regex can match strings with only one character.
So use standard character class [a-zA-Z'. ] and to let your regex match strings one or more characters use + quantifier.
System.out.println(str.matches("[a-zA-Z'. ]+"));
You can try this one [\p{Alpha}\s'.]*

match whole sentence with regex

I'm trying to match sentences without capital letters with regex in Java:
"Hi this is a test" -> Shouldn't match
"hi thiS is a test" -> Shouldn't match
"hi this is a test" -> Should match
I've tried the following regex, but it also matches my second example ("hi, thiS is a test").
[a-z]+
It seems like it's only looking at the first word of the sentence.
Any help?
[a-z]+ will match if your string contains any lowercase letter.
If you want to make sure your string doesn't contain uppercase letters, you could use a negative character class: ^[^A-Z]+$
Be aware that this won't handle accentuated characters (like É) though.
To make this work, you can use Unicode properties: ^\P{Lu}+$
\P means is not in Unicode category, and Lu is the uppercase letter that has a lowercase variant category.
^[a-z ]+$
Try this.This will validate the right ones.
It's not matching because you haven't used a space in the match pattern, so your regex is only matching whole words with no spaces.
try something like ^[a-z ]+$ instead (notice the space is the square brackets) you can also use \s which is shorthand for 'whitespace characters' but this can also include things like line feeds and carriage returns so just be aware.
This pattern does the following:
^ matches the start of a string
[a-z ]+ matches any a-z character or a space, where 1 or more exists.
$ matches the end of the string.
I would actually advise against regex in this case, since you don't seem to employ extended characters.
Instead try to test as following:
myString.equals(myString.toLowerCase());

Check string contains whitespace along with some other char sequence using regex in java

am using regex expression to check if a string contains white space.
my regex is : ^\\s+$
for example if my string is my name then regex matches should return true.
but it is returning true only if my string contains only spaces no other character.
How to check if a string contains a whitespace or tab or carriage return characters in between/start/end of some string.
^(.*\s+.*)+$ seems to work for me. Accepts anything as long as there is at least one space in the string. This will match the entire string.
If you only want to check for the presence of a space, you can just use \s without any begin or end markers in the string. The difference is that this will only match the individual spaces.
Your regex is not correct.
That's a string representing a regular expression. (as tchrist pointed out correctly)
The corresponding pattern that you get when using Pattern.compile() matches only strings containing one or more whitespace characters, starting from the beginning until the end. Thus, the matching string only consists of whitespace characters.
Try this string instead for Pattern.compile():
"\\s+"
The difference is that without the anchors "^" and "$" there may be other characters around the whitespace character. The whitespace character(s) may be everywhere in the string.
Using this pattern-string the whitespace character(s) must be at the beginning:
"^\\s+"
And here the sequence of whitespace characters has to be at the end:
"\\s+$"
Use org.apache.commons.lang.StringUtils.containsAny(). See http://commons.apache.org/lang/api-3.1/org/apache/commons/lang3/StringUtils.html.

Regex for matching alternating sequences

I'm working in Java and having trouble matching a repeated sequence. I'd like to match something like:
a.b.c.d.e.f.g.
and be able to extract the text between the delimiters (e.g. return abcdefg) where the delimiter can be multiple non-word characters and the text can be multiple word characters. Here is my regex so far:
([\\w]+([\\W]+)(?:[\\w]+\2)*)
(Doesn't work)
I had intended to get the delimiter in group 2 with this regex and then use a replaceAll on group 1 to exchange the delimiter for the empty string giving me the text only. I get the delimiter, but cannot get all the text.
Thanks for any help!
Replace (\w+)\W+ by $1
Replace (\w+)(\W+|$) with $1. Make sure that global flag is turned on.
It replaces a sequence of word chars followed by a sequence of non-word-chars or end-of-line with the sequence of words.
String line = "Am.$#%^ar.$#%^gho.$#%^sh";
line = line.replaceAll("(\\w+)(\\W+|$)", "$1");
System.out.println(line);//prints my name
Why not use String.split?
Why not ..
find all occurences of (\w+) and then concatenate them; or
find all non word characters (\W+) and then use Matcher.html#replaceAll with an empty string?

Categories

Resources