简体   繁体   中英

Regex - Replace single character after a string in scala

I have a text similar to:

"ciao cos? come stai??"

And I'd want to replace (in Scala using Regex) only one question mark after a sequence of characters (ie [a-zA-Z0-9]) with another character. So in the previous example if we suppose that I want to replace "?" with "_", the result should be:

"ciao cos_ come stai_?"

Edit : Yes, I tried some solution found also on SO, like this in this link . In Scala I tried:

val text = "some? ??"
val regex = "/([a-zA-Z0-9])?/".r
val text11 =regex.replaceAllIn(text, "_")

But also:

val text = "some? ??"
val regex = "/([a-zA-Z0-9])?([a-zA-Z0-9])/".r
val text11 =regex.replaceAllIn(text, "_")

And the original one posted in the previous link with another string in input but it doesn't work.

Thanks

I don't know about scala, but after some research I manage to build something for you.

Here the regex if you want to deal only with english characters

val str = "ciao cos? come stai??".replaceAll("""((?i)[A-Z]+)\?""", "$1_");

Explanation :

  • (?i) : Means case insensitive.
  • [AZ]+ : One or more english letter
  • () : Capture group
  • ((?i)[AZ]+) : capture one or more english letter (no matter the case)
  • (\\?) : Capture the literal character '?' in the second group (it have to be escaped with a backslash because the question mark have a special meaning in the regex).
  • ((?i)[AZ]+)\\? : Capture as much letters as you can in the first capture group immediately followed by a question mark captured by the second capture group.

  • $1 : Put the content of the first capture group

  • $1_ : Put the content of the first capture group followed by an underscore. The question mark will disappear.

To deal with any letters from any languages (by example the french letter "é" you can use this:

val str = "j'aime le karaté?".replaceAll("""(\p{L}+)\?""", "$1_");
  • \\p{L} : That stand for any unicode letter in any case.

I used this site to test the regexes:

http://www.tryscala.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM