Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex all characters except last

Tags:

regex

I want to place a dash after every letter but my regex place a dash at the end too. How can I improve my regex?

String outputS = dnaString.replaceAll("(.{1})", "$1-");
like image 922
ocram Avatar asked Oct 24 '15 19:10

ocram


People also ask

How do you match a character except in regex?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '. ' (period) is a metacharacter (it sometimes has a special meaning).

What does \+ mean in regex?

Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol. Example: "^a" matches "a" at the start of the string.

What regex matches any character?

Matching a Single Character Using Regex By default, the '. ' dot character in a regular expression matches a single character without regard to what character it is. The matched character can be an alphabet, a number or, any special character.


1 Answers

(.)(?!$)

You can use this.Replace by $1.See demo.

https://regex101.com/r/gT6vU5/11

(?!$) uses negative lookahead to state that do not capture a character which is at end of string.

like image 80
vks Avatar answered Nov 30 '22 23:11

vks