繁体   English   中英

正确替换所有孤立的字符串

[英]ReplaceAll isolated string correctly

我正在使用翻译器应用程序,但遇到了一个小问题。 例如:当我type Hond ,我希望outputDog ;当我type Honderd ,我希望outputHundred 但是当我输入Dogerd时,我得到了Dogerd 因此,它只需要翻译Hond并添加其余字母即可。 通过在代码中将Honderd放在Hond之上,我想出了一个解决方案。 但是必须对此问题有另一种解决方案吗? 这是代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mType = (EditText) findViewById(R.id.typeWordTxt);
    mSearch = (Button) findViewById(R.id.find8tn);
    mResults = (TextView) findViewById(R.id.resultsTxt);

    mSearch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String resultaat = mType.getText().toString().toLowerCase();
            resultaat = resultaat
                    //Getallen
                    .replaceAll("honderd", "hundred")
                    .replaceAll("hond", "dog")
            mResults.setText(resultaat);

谢谢您的帮助!

您可以使用\\\\b单词边界将您的单词隔离为单个单词,而不是将其与其他单词匹配

\\\\bhonderd\\\\b\\\\bhond\\\\b

    String s ="Honderd Honderd Hond".toLowerCase();
    System.out.println(s
            .replaceAll("\\bhond\\b", "dog")
            .replaceAll("\\bhonderd\\b", "hundred"));

输出:

hundred hundred dog

演示

 const honderd_rep = /\\bhonderd\\b/g; const hond_rep = /\\bhond\\b/g; const str = 'honderd honderd hond'; const result = str.replace(hond_rep,'dog').replace(honderd_rep, 'hundred'); console.log(result); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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