Java Regex ReplaceAll with grouping - java

I want to surround all tokens in a text with tags in the following manner:
Input: " abc fg asd "
Output:" <token>abc</token> <token>fg</token> <token>asd</token> "
This is the code I tried so far:
String regex = "(\\s)([a-zA-Z]+)(\\s)";
String text = " abc fg asd ";
text = text.replaceAll(regex, "$1<token>$2</token>$3");
System.out.println(text);
Output:" <token>abc</token> fg <token>asd</token> "
Note: for simplicity we can assume that the input starts and ends with whitespaces

Use lookaround:
String regex = "(?<=\\s)([a-zA-Z]+)(?=\\s)";
...
text = text.replaceAll(regex, "<token>$1</token>");

If your tokens are only defined with a character class you don't need to describe what characters are around. So this should suffice since the regex engine walks from left to right and since the quantifier is greedy:
String regex = "[a-zA-Z]+";
text = text.replaceAll(regex, "<token>$0</token>");

// meaning not a space, 1+ times
String result = input.replaceAll("([^\\s]+)", "<token>$1</token>");
this matches everything that isn't a space. Prolly the best fit for what you need. Also it's greedy meaning it will never leave out a character that it shouldn't ( it will never find the string "as" in the string "asd" when there is another character with which it matches)

Related

Java Split String by colon on both side

Can you suggest me an approach by which I can split a String which is like:
:31C:150318
:31D:150425 IN BANGLADESH
:20:314015040086
So I tried to parse that string with
:[A-za-z]|\\d:
This kind of regular expression, but it is not working . Please suggest me a regular expression by which I can split that string with 20 , 31C , 31D etc as Keys and 150318 , 150425 IN BANGLADESH etc as Values .
If I use string.split(":") then it would not serve my purpose.
If a string is like:
:20: MY VALUES : ARE HERE
then It will split up into 3 string , and key 20 will be associated with "MY VALUES" , and "ARE HERE" will not associated with key 20 .
You may use matching mechanism instead of splitting since you need to match a specific colon in the string.
The regex to get 2 groups between the first and second colon and also capture everything after the second colon will look like
^:([^:]*):(.*)$
See demo. The ^ will assert the beginning of the string, ([^:]*) will match and capture into Group 1 zero or more characters other than :, and (.*) will match and capture into Group 2 the rest of the string. $ will assert the position at the end of a single line string (as . matches any symbol but a newline without Pattern.DOTALL modifier).
String s = ":20:AND:HERE";
Pattern pattern = Pattern.compile("^:([^:]*):(.*)$");
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println("Key: " + matcher.group(1) + ", Value: " + matcher.group(2) + "\n");
}
Result for this demo: Key: 20, Value: AND:HERE
You can use the following to split:
^[:]+([^:]+):
Try with split function of String class
String[] splited = string.split(":");
For your requirements:
String c = ":31D:150425 IN BANGLADESH:todasdsa";
c=c.substring(1);
System.out.println("C="+c);
String key= c.substring(0,c.indexOf(":"));
String value = c.substring(c.indexOf(":")+1);
System.out.println("key="+key+" value="+value);
Result:
C=31D:150425 IN BANGLADESH:todasdsa
key=31D value=150425 IN BANGLADESH:todasdsa

How do I expand this replace expression to add weird alpha characters like "ü"?

I have this replacement expression here:
String firstName = mFirstName.getText().toString().trim().replace(" ", "");
String lastName = mLastName.getText().toString().trim().replace(" ", "");
firstName = firstName.replaceAll("[^A-Za-z'-]", "");
lastName = lastName.replaceAll("[^A-Za-z'-]", "");
It works really well and quickly. However it doesn't allow for the international ascii characters 128-165, say like umlauts. But I don't want the characters after that "()|-" in the string to be included. Is there a way to include that all in one replace all, or do I have to separate it out into multiple expressions?
Here's what I've tried (unsuccessfully) :
firstName = firstName.replaceAll("[^A-Za-zÀ-Ÿ'-]", "");
lastName = lastName.replaceAll("[^Alpha'-]", "");
It still replaces the characters.
You can use \p{L} which matches any Unicode character which is letter.
String strUmlaut = "ÀèŸ";
System.out.println(strUmlaut.matches("\\p{L}+"));
OUTPUT
true
[^A-Za-z\\x80-\\xa5'-] will additionally match characters with ASCII codes 128-165 (80 - A5 in hex)

find two consecutive words/strings with regex expression java (including punctuation)

I want to check wheter a string is containing two words/string directly followed in a specific order.
The punctuation should also be included in the word/string. (i.e. "word" and "word." should be handeled as different words).
As an example:
String word1 = "is";
String word1 = "a";
String text = "This is a sample";
Pattern p = Pattern.compile(someregex+"+word1+"someregex"+word2+"someregex");
System.out.println(p.matcher(text).matches());
This should print out true.
With the following variables, it should also print true.
String word1 = "sample.";
String word1 = "0END";
String text = "This is a sample. 0END0";
But the latter should return false when setting word1 = "sample" (without punctuation).
Does anyone have an idea how the regex string should look like (i.e. what i should write instead of "someregex" ?)
Thank you!
Looks like you're just splitting on whitespace, try:
Pattern p = Pattern.compile("(\\s|^)" + Pattern.quote(word1) + "\\s+" + Pattern.quote(word2) + "(\\s|$)");
Explaination
(\\s|^) matches any whitespace before the first word, or the start of the string
\\s+ matches the whitespace between the words
(\\s|$) matches any whitespace after the second word, or the end of the string
Pattern.quote(...) ensures that any regex special characters in your input strings are properly escapes.
You also need to call find(), not match(). match() will only return true if the whole string matches the pattern.
Complete example
String word1 = "is";
String word2 = "a";
String text = "This is a sample";
String regex =
"(\\s|^)" +
Pattern.quote(word1) +
"\\s+" +
Pattern.quote(word2) +
"(\\s|$)";
Pattern p = Pattern.compile(regex);
System.out.println(p.matcher(text).find());
You can concatenate the two words with a whitespace and use that as the regexp.
the only thing, you have to do, is to replace "." with "." so the point does not match as any character.
String regexp = " " + word1 + " " + word2 + " ";
regexp = regexp.replaceAll("\\.", "\\\\.");

How to remove spaces in between the String

I have below String
string = "Book Your Domain And Get\n \n\n \n \n \n Online Today."
string = str.replace("\\s","").trim();
which returning
str = "Book Your Domain And Get Online Today."
But what is want is
str = "Book Your Domain And Get Online Today."
I have tried Many Regular Expression and also googled but got no luck. and did't find related question, Please Help, Many Thanks in Advance
Use \\s+ instead of \\s as there are two or more consecutive whitespaces in your input.
string = str.replaceAll("\\s+"," ")
You can use replaceAll which takes a regex as parameter. And it seems like you want to replace multiple spaces with a single space. You can do it like this:
string = str.replaceAll("\\s{2,}"," ");
It will replace 2 or more consecutive whitespaces with a single whitespace.
First get rid of multiple spaces:
String after = before.trim().replaceAll(" +", " ");
If you want to just remove the white space between 2 words or characters and not at the end of string
then here is the
regex that i have used,
String s = " N OR 15 2 ";
Pattern pattern = Pattern.compile("[a-zA-Z0-9]\\s+[a-zA-Z0-9]", Pattern.CASE_INSENSITIVE);
Matcher m = pattern.matcher(s);
while(m.find()){
String replacestr = "";
int i = m.start();
while(i<m.end()){
replacestr = replacestr + s.charAt(i);
i++;
}
m = pattern.matcher(s);
}
System.out.println(s);
it will only remove the space between characters or words not spaces at the ends
and the output is
NOR152
Eg. to remove space between words in a string:
String example = "Interactive Resource";
System.out.println("Without space string: "+ example.replaceAll("\\s",""));
Output:
Without space string: InteractiveResource
If you want to print a String without space, just add the argument sep='' to the print function, since this argument's default value is " ".
//user this for removing all the whitespaces from a given string for example a =" 1 2 3 4"
//output: 1234
a.replaceAll("\\s", "")
String s2=" 1 2 3 4 5 ";
String after=s2.replace(" ", "");
this work for me
String string_a = "AAAA BBB";
String actualTooltip_3 = string_a.replaceAll("\\s{2,}"," ");
System.out.println(String actualTooltip_3);
OUTPUT will be:AAA BBB

how to check if a space is followed by a certain character?

I am really confused on this regex things. I have tried to understand it, went no where.
Basically, i am trying to replace all spaces followed by every character but a space to be replaced with "PM".
" sd"
" sd"
however
" sd"
" sd"
This will replace the space and the following character with "PM":
String s = "123 axy cq23 dasd"; //your string
String newString = s.replaceAll(" [^ ]","PM");
Since I'm not sure if you want to replace only the space or the space and the following character, too, here is a slightly modified version that replaces only the space:
String s = "123 axy cq23 dasd"; //your string
String newString = s.replaceAll(" ([^ ])", "PM$1")
You need to use non-capturing pattern:
String res = oldString.replaceAll(" (?:[^ ])", "PM");

Categories

Resources